000001 /*
000002 ** 2003 September 6
000003 **
000004 ** The author disclaims copyright to this source code. In place of
000005 ** a legal notice, here is a blessing:
000006 **
000007 ** May you do good and not evil.
000008 ** May you find forgiveness for yourself and forgive others.
000009 ** May you share freely, never taking more than you give.
000010 **
000011 *************************************************************************
000012 ** This file contains code used for creating, destroying, and populating
000013 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
000014 */
000015 #include "sqliteInt.h"
000016 #include "vdbeInt.h"
000017
000018 /* Forward references */
000019 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
000020 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
000021
000022 /*
000023 ** Create a new virtual database engine.
000024 */
000025 Vdbe *sqlite3VdbeCreate(Parse *pParse){
000026 sqlite3 *db = pParse->db;
000027 Vdbe *p;
000028 p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
000029 if( p==0 ) return 0;
000030 memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
000031 p->db = db;
000032 if( db->pVdbe ){
000033 db->pVdbe->ppVPrev = &p->pVNext;
000034 }
000035 p->pVNext = db->pVdbe;
000036 p->ppVPrev = &db->pVdbe;
000037 db->pVdbe = p;
000038 assert( p->eVdbeState==VDBE_INIT_STATE );
000039 p->pParse = pParse;
000040 pParse->pVdbe = p;
000041 assert( pParse->aLabel==0 );
000042 assert( pParse->nLabel==0 );
000043 assert( p->nOpAlloc==0 );
000044 assert( pParse->szOpAlloc==0 );
000045 sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
000046 return p;
000047 }
000048
000049 /*
000050 ** Return the Parse object that owns a Vdbe object.
000051 */
000052 Parse *sqlite3VdbeParser(Vdbe *p){
000053 return p->pParse;
000054 }
000055
000056 /*
000057 ** Change the error string stored in Vdbe.zErrMsg
000058 */
000059 void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
000060 va_list ap;
000061 sqlite3DbFree(p->db, p->zErrMsg);
000062 va_start(ap, zFormat);
000063 p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
000064 va_end(ap);
000065 }
000066
000067 /*
000068 ** Remember the SQL string for a prepared statement.
000069 */
000070 void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
000071 if( p==0 ) return;
000072 p->prepFlags = prepFlags;
000073 if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
000074 p->expmask = 0;
000075 }
000076 assert( p->zSql==0 );
000077 p->zSql = sqlite3DbStrNDup(p->db, z, n);
000078 }
000079
000080 #ifdef SQLITE_ENABLE_NORMALIZE
000081 /*
000082 ** Add a new element to the Vdbe->pDblStr list.
000083 */
000084 void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
000085 if( p ){
000086 int n = sqlite3Strlen30(z);
000087 DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
000088 sizeof(*pStr)+n+1-sizeof(pStr->z));
000089 if( pStr ){
000090 pStr->pNextStr = p->pDblStr;
000091 p->pDblStr = pStr;
000092 memcpy(pStr->z, z, n+1);
000093 }
000094 }
000095 }
000096 #endif
000097
000098 #ifdef SQLITE_ENABLE_NORMALIZE
000099 /*
000100 ** zId of length nId is a double-quoted identifier. Check to see if
000101 ** that identifier is really used as a string literal.
000102 */
000103 int sqlite3VdbeUsesDoubleQuotedString(
000104 Vdbe *pVdbe, /* The prepared statement */
000105 const char *zId /* The double-quoted identifier, already dequoted */
000106 ){
000107 DblquoteStr *pStr;
000108 assert( zId!=0 );
000109 if( pVdbe->pDblStr==0 ) return 0;
000110 for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
000111 if( strcmp(zId, pStr->z)==0 ) return 1;
000112 }
000113 return 0;
000114 }
000115 #endif
000116
000117 /*
000118 ** Swap byte-code between two VDBE structures.
000119 **
000120 ** This happens after pB was previously run and returned
000121 ** SQLITE_SCHEMA. The statement was then reprepared in pA.
000122 ** This routine transfers the new bytecode in pA over to pB
000123 ** so that pB can be run again. The old pB byte code is
000124 ** moved back to pA so that it will be cleaned up when pA is
000125 ** finalized.
000126 */
000127 void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
000128 Vdbe tmp, *pTmp, **ppTmp;
000129 char *zTmp;
000130 assert( pA->db==pB->db );
000131 tmp = *pA;
000132 *pA = *pB;
000133 *pB = tmp;
000134 pTmp = pA->pVNext;
000135 pA->pVNext = pB->pVNext;
000136 pB->pVNext = pTmp;
000137 ppTmp = pA->ppVPrev;
000138 pA->ppVPrev = pB->ppVPrev;
000139 pB->ppVPrev = ppTmp;
000140 zTmp = pA->zSql;
000141 pA->zSql = pB->zSql;
000142 pB->zSql = zTmp;
000143 #ifdef SQLITE_ENABLE_NORMALIZE
000144 zTmp = pA->zNormSql;
000145 pA->zNormSql = pB->zNormSql;
000146 pB->zNormSql = zTmp;
000147 #endif
000148 pB->expmask = pA->expmask;
000149 pB->prepFlags = pA->prepFlags;
000150 memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
000151 pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
000152 }
000153
000154 /*
000155 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
000156 ** than its current size. nOp is guaranteed to be less than or equal
000157 ** to 1024/sizeof(Op).
000158 **
000159 ** If an out-of-memory error occurs while resizing the array, return
000160 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
000161 ** unchanged (this is so that any opcodes already allocated can be
000162 ** correctly deallocated along with the rest of the Vdbe).
000163 */
000164 static int growOpArray(Vdbe *v, int nOp){
000165 VdbeOp *pNew;
000166 Parse *p = v->pParse;
000167
000168 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
000169 ** more frequent reallocs and hence provide more opportunities for
000170 ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
000171 ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
000172 ** by the minimum* amount required until the size reaches 512. Normal
000173 ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
000174 ** size of the op array or add 1KB of space, whichever is smaller. */
000175 #ifdef SQLITE_TEST_REALLOC_STRESS
000176 sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
000177 : (sqlite3_int64)v->nOpAlloc+nOp);
000178 #else
000179 sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
000180 : (sqlite3_int64)(1024/sizeof(Op)));
000181 UNUSED_PARAMETER(nOp);
000182 #endif
000183
000184 /* Ensure that the size of a VDBE does not grow too large */
000185 if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
000186 sqlite3OomFault(p->db);
000187 return SQLITE_NOMEM;
000188 }
000189
000190 assert( nOp<=(int)(1024/sizeof(Op)) );
000191 assert( nNew>=(v->nOpAlloc+nOp) );
000192 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
000193 if( pNew ){
000194 p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
000195 v->nOpAlloc = p->szOpAlloc/sizeof(Op);
000196 v->aOp = pNew;
000197 }
000198 return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
000199 }
000200
000201 #ifdef SQLITE_DEBUG
000202 /* This routine is just a convenient place to set a breakpoint that will
000203 ** fire after each opcode is inserted and displayed using
000204 ** "PRAGMA vdbe_addoptrace=on". Parameters "pc" (program counter) and
000205 ** pOp are available to make the breakpoint conditional.
000206 **
000207 ** Other useful labels for breakpoints include:
000208 ** test_trace_breakpoint(pc,pOp)
000209 ** sqlite3CorruptError(lineno)
000210 ** sqlite3MisuseError(lineno)
000211 ** sqlite3CantopenError(lineno)
000212 */
000213 static void test_addop_breakpoint(int pc, Op *pOp){
000214 static u64 n = 0;
000215 (void)pc;
000216 (void)pOp;
000217 n++;
000218 if( n==LARGEST_UINT64 ) abort(); /* so that n is used, preventing a warning */
000219 }
000220 #endif
000221
000222 /*
000223 ** Slow paths for sqlite3VdbeAddOp3() and sqlite3VdbeAddOp4Int() for the
000224 ** unusual case when we need to increase the size of the Vdbe.aOp[] array
000225 ** before adding the new opcode.
000226 */
000227 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
000228 assert( p->nOpAlloc<=p->nOp );
000229 if( growOpArray(p, 1) ) return 1;
000230 assert( p->nOpAlloc>p->nOp );
000231 return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
000232 }
000233 static SQLITE_NOINLINE int addOp4IntSlow(
000234 Vdbe *p, /* Add the opcode to this VM */
000235 int op, /* The new opcode */
000236 int p1, /* The P1 operand */
000237 int p2, /* The P2 operand */
000238 int p3, /* The P3 operand */
000239 int p4 /* The P4 operand as an integer */
000240 ){
000241 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
000242 if( p->db->mallocFailed==0 ){
000243 VdbeOp *pOp = &p->aOp[addr];
000244 pOp->p4type = P4_INT32;
000245 pOp->p4.i = p4;
000246 }
000247 return addr;
000248 }
000249
000250
000251 /*
000252 ** Add a new instruction to the list of instructions current in the
000253 ** VDBE. Return the address of the new instruction.
000254 **
000255 ** Parameters:
000256 **
000257 ** p Pointer to the VDBE
000258 **
000259 ** op The opcode for this instruction
000260 **
000261 ** p1, p2, p3, p4 Operands
000262 */
000263 int sqlite3VdbeAddOp0(Vdbe *p, int op){
000264 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
000265 }
000266 int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
000267 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
000268 }
000269 int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
000270 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
000271 }
000272 int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
000273 int i;
000274 VdbeOp *pOp;
000275
000276 i = p->nOp;
000277 assert( p->eVdbeState==VDBE_INIT_STATE );
000278 assert( op>=0 && op<0xff );
000279 if( p->nOpAlloc<=i ){
000280 return growOp3(p, op, p1, p2, p3);
000281 }
000282 assert( p->aOp!=0 );
000283 p->nOp++;
000284 pOp = &p->aOp[i];
000285 assert( pOp!=0 );
000286 pOp->opcode = (u8)op;
000287 pOp->p5 = 0;
000288 pOp->p1 = p1;
000289 pOp->p2 = p2;
000290 pOp->p3 = p3;
000291 pOp->p4.p = 0;
000292 pOp->p4type = P4_NOTUSED;
000293
000294 /* Replicate this logic in sqlite3VdbeAddOp4Int()
000295 ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
000296 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
000297 pOp->zComment = 0;
000298 #endif
000299 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
000300 pOp->nExec = 0;
000301 pOp->nCycle = 0;
000302 #endif
000303 #ifdef SQLITE_DEBUG
000304 if( p->db->flags & SQLITE_VdbeAddopTrace ){
000305 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
000306 test_addop_breakpoint(i, &p->aOp[i]);
000307 }
000308 #endif
000309 #ifdef SQLITE_VDBE_COVERAGE
000310 pOp->iSrcLine = 0;
000311 #endif
000312 /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
000313 ** Replicate in sqlite3VdbeAddOp4Int() */
000314
000315 return i;
000316 }
000317 int sqlite3VdbeAddOp4Int(
000318 Vdbe *p, /* Add the opcode to this VM */
000319 int op, /* The new opcode */
000320 int p1, /* The P1 operand */
000321 int p2, /* The P2 operand */
000322 int p3, /* The P3 operand */
000323 int p4 /* The P4 operand as an integer */
000324 ){
000325 int i;
000326 VdbeOp *pOp;
000327
000328 i = p->nOp;
000329 if( p->nOpAlloc<=i ){
000330 return addOp4IntSlow(p, op, p1, p2, p3, p4);
000331 }
000332 p->nOp++;
000333 pOp = &p->aOp[i];
000334 assert( pOp!=0 );
000335 pOp->opcode = (u8)op;
000336 pOp->p5 = 0;
000337 pOp->p1 = p1;
000338 pOp->p2 = p2;
000339 pOp->p3 = p3;
000340 pOp->p4.i = p4;
000341 pOp->p4type = P4_INT32;
000342
000343 /* Replicate this logic in sqlite3VdbeAddOp3()
000344 ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
000345 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
000346 pOp->zComment = 0;
000347 #endif
000348 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)
000349 pOp->nExec = 0;
000350 pOp->nCycle = 0;
000351 #endif
000352 #ifdef SQLITE_DEBUG
000353 if( p->db->flags & SQLITE_VdbeAddopTrace ){
000354 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
000355 test_addop_breakpoint(i, &p->aOp[i]);
000356 }
000357 #endif
000358 #ifdef SQLITE_VDBE_COVERAGE
000359 pOp->iSrcLine = 0;
000360 #endif
000361 /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
000362 ** Replicate in sqlite3VdbeAddOp3() */
000363
000364 return i;
000365 }
000366
000367 /* Generate code for an unconditional jump to instruction iDest
000368 */
000369 int sqlite3VdbeGoto(Vdbe *p, int iDest){
000370 return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
000371 }
000372
000373 /* Generate code to cause the string zStr to be loaded into
000374 ** register iDest
000375 */
000376 int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
000377 return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
000378 }
000379
000380 /*
000381 ** Generate code that initializes multiple registers to string or integer
000382 ** constants. The registers begin with iDest and increase consecutively.
000383 ** One register is initialized for each characgter in zTypes[]. For each
000384 ** "s" character in zTypes[], the register is a string if the argument is
000385 ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
000386 ** in zTypes[], the register is initialized to an integer.
000387 **
000388 ** If the input string does not end with "X" then an OP_ResultRow instruction
000389 ** is generated for the values inserted.
000390 */
000391 void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
000392 va_list ap;
000393 int i;
000394 char c;
000395 va_start(ap, zTypes);
000396 for(i=0; (c = zTypes[i])!=0; i++){
000397 if( c=='s' ){
000398 const char *z = va_arg(ap, const char*);
000399 sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
000400 }else if( c=='i' ){
000401 sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
000402 }else{
000403 goto skip_op_resultrow;
000404 }
000405 }
000406 sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
000407 skip_op_resultrow:
000408 va_end(ap);
000409 }
000410
000411 /*
000412 ** Add an opcode that includes the p4 value as a pointer.
000413 */
000414 int sqlite3VdbeAddOp4(
000415 Vdbe *p, /* Add the opcode to this VM */
000416 int op, /* The new opcode */
000417 int p1, /* The P1 operand */
000418 int p2, /* The P2 operand */
000419 int p3, /* The P3 operand */
000420 const char *zP4, /* The P4 operand */
000421 int p4type /* P4 operand type */
000422 ){
000423 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
000424 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
000425 return addr;
000426 }
000427
000428 /*
000429 ** Add an OP_Function or OP_PureFunc opcode.
000430 **
000431 ** The eCallCtx argument is information (typically taken from Expr.op2)
000432 ** that describes the calling context of the function. 0 means a general
000433 ** function call. NC_IsCheck means called by a check constraint,
000434 ** NC_IdxExpr means called as part of an index expression. NC_PartIdx
000435 ** means in the WHERE clause of a partial index. NC_GenCol means called
000436 ** while computing a generated column value. 0 is the usual case.
000437 */
000438 int sqlite3VdbeAddFunctionCall(
000439 Parse *pParse, /* Parsing context */
000440 int p1, /* Constant argument mask */
000441 int p2, /* First argument register */
000442 int p3, /* Register into which results are written */
000443 int nArg, /* Number of argument */
000444 const FuncDef *pFunc, /* The function to be invoked */
000445 int eCallCtx /* Calling context */
000446 ){
000447 Vdbe *v = pParse->pVdbe;
000448 int nByte;
000449 int addr;
000450 sqlite3_context *pCtx;
000451 assert( v );
000452 nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
000453 pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
000454 if( pCtx==0 ){
000455 assert( pParse->db->mallocFailed );
000456 freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
000457 return 0;
000458 }
000459 pCtx->pOut = 0;
000460 pCtx->pFunc = (FuncDef*)pFunc;
000461 pCtx->pVdbe = 0;
000462 pCtx->isError = 0;
000463 pCtx->argc = nArg;
000464 pCtx->iOp = sqlite3VdbeCurrentAddr(v);
000465 addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
000466 p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
000467 sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
000468 sqlite3MayAbort(pParse);
000469 return addr;
000470 }
000471
000472 /*
000473 ** Add an opcode that includes the p4 value with a P4_INT64 or
000474 ** P4_REAL type.
000475 */
000476 int sqlite3VdbeAddOp4Dup8(
000477 Vdbe *p, /* Add the opcode to this VM */
000478 int op, /* The new opcode */
000479 int p1, /* The P1 operand */
000480 int p2, /* The P2 operand */
000481 int p3, /* The P3 operand */
000482 const u8 *zP4, /* The P4 operand */
000483 int p4type /* P4 operand type */
000484 ){
000485 char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
000486 if( p4copy ) memcpy(p4copy, zP4, 8);
000487 return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
000488 }
000489
000490 #ifndef SQLITE_OMIT_EXPLAIN
000491 /*
000492 ** Return the address of the current EXPLAIN QUERY PLAN baseline.
000493 ** 0 means "none".
000494 */
000495 int sqlite3VdbeExplainParent(Parse *pParse){
000496 VdbeOp *pOp;
000497 if( pParse->addrExplain==0 ) return 0;
000498 pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
000499 return pOp->p2;
000500 }
000501
000502 /*
000503 ** Set a debugger breakpoint on the following routine in order to
000504 ** monitor the EXPLAIN QUERY PLAN code generation.
000505 */
000506 #if defined(SQLITE_DEBUG)
000507 void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
000508 (void)z1;
000509 (void)z2;
000510 }
000511 #endif
000512
000513 /*
000514 ** Add a new OP_Explain opcode.
000515 **
000516 ** If the bPush flag is true, then make this opcode the parent for
000517 ** subsequent Explains until sqlite3VdbeExplainPop() is called.
000518 */
000519 int sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
000520 int addr = 0;
000521 #if !defined(SQLITE_DEBUG)
000522 /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
000523 ** But omit them (for performance) during production builds */
000524 if( pParse->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
000525 #endif
000526 {
000527 char *zMsg;
000528 Vdbe *v;
000529 va_list ap;
000530 int iThis;
000531 va_start(ap, zFmt);
000532 zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
000533 va_end(ap);
000534 v = pParse->pVdbe;
000535 iThis = v->nOp;
000536 addr = sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
000537 zMsg, P4_DYNAMIC);
000538 sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetLastOp(v)->p4.z);
000539 if( bPush){
000540 pParse->addrExplain = iThis;
000541 }
000542 sqlite3VdbeScanStatus(v, iThis, -1, -1, 0, 0);
000543 }
000544 return addr;
000545 }
000546
000547 /*
000548 ** Pop the EXPLAIN QUERY PLAN stack one level.
000549 */
000550 void sqlite3VdbeExplainPop(Parse *pParse){
000551 sqlite3ExplainBreakpoint("POP", 0);
000552 pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
000553 }
000554 #endif /* SQLITE_OMIT_EXPLAIN */
000555
000556 /*
000557 ** Add an OP_ParseSchema opcode. This routine is broken out from
000558 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
000559 ** as having been used.
000560 **
000561 ** The zWhere string must have been obtained from sqlite3_malloc().
000562 ** This routine will take ownership of the allocated memory.
000563 */
000564 void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere, u16 p5){
000565 int j;
000566 sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
000567 sqlite3VdbeChangeP5(p, p5);
000568 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
000569 sqlite3MayAbort(p->pParse);
000570 }
000571
000572 /* Insert the end of a co-routine
000573 */
000574 void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
000575 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
000576
000577 /* Clear the temporary register cache, thereby ensuring that each
000578 ** co-routine has its own independent set of registers, because co-routines
000579 ** might expect their registers to be preserved across an OP_Yield, and
000580 ** that could cause problems if two or more co-routines are using the same
000581 ** temporary register.
000582 */
000583 v->pParse->nTempReg = 0;
000584 v->pParse->nRangeReg = 0;
000585 }
000586
000587 /*
000588 ** Create a new symbolic label for an instruction that has yet to be
000589 ** coded. The symbolic label is really just a negative number. The
000590 ** label can be used as the P2 value of an operation. Later, when
000591 ** the label is resolved to a specific address, the VDBE will scan
000592 ** through its operation list and change all values of P2 which match
000593 ** the label into the resolved address.
000594 **
000595 ** The VDBE knows that a P2 value is a label because labels are
000596 ** always negative and P2 values are suppose to be non-negative.
000597 ** Hence, a negative P2 value is a label that has yet to be resolved.
000598 ** (Later:) This is only true for opcodes that have the OPFLG_JUMP
000599 ** property.
000600 **
000601 ** Variable usage notes:
000602 **
000603 ** Parse.aLabel[x] Stores the address that the x-th label resolves
000604 ** into. For testing (SQLITE_DEBUG), unresolved
000605 ** labels stores -1, but that is not required.
000606 ** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]
000607 ** Parse.nLabel The *negative* of the number of labels that have
000608 ** been issued. The negative is stored because
000609 ** that gives a performance improvement over storing
000610 ** the equivalent positive value.
000611 */
000612 int sqlite3VdbeMakeLabel(Parse *pParse){
000613 return --pParse->nLabel;
000614 }
000615
000616 /*
000617 ** Resolve label "x" to be the address of the next instruction to
000618 ** be inserted. The parameter "x" must have been obtained from
000619 ** a prior call to sqlite3VdbeMakeLabel().
000620 */
000621 static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
000622 int nNewSize = 10 - p->nLabel;
000623 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
000624 nNewSize*sizeof(p->aLabel[0]));
000625 if( p->aLabel==0 ){
000626 p->nLabelAlloc = 0;
000627 }else{
000628 #ifdef SQLITE_DEBUG
000629 int i;
000630 for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
000631 #endif
000632 if( nNewSize>=100 && (nNewSize/100)>(p->nLabelAlloc/100) ){
000633 sqlite3ProgressCheck(p);
000634 }
000635 p->nLabelAlloc = nNewSize;
000636 p->aLabel[j] = v->nOp;
000637 }
000638 }
000639 void sqlite3VdbeResolveLabel(Vdbe *v, int x){
000640 Parse *p = v->pParse;
000641 int j = ADDR(x);
000642 assert( v->eVdbeState==VDBE_INIT_STATE );
000643 assert( j<-p->nLabel );
000644 assert( j>=0 );
000645 #ifdef SQLITE_DEBUG
000646 if( p->db->flags & SQLITE_VdbeAddopTrace ){
000647 printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
000648 }
000649 #endif
000650 if( p->nLabelAlloc + p->nLabel < 0 ){
000651 resizeResolveLabel(p,v,j);
000652 }else{
000653 assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
000654 p->aLabel[j] = v->nOp;
000655 }
000656 }
000657
000658 /*
000659 ** Mark the VDBE as one that can only be run one time.
000660 */
000661 void sqlite3VdbeRunOnlyOnce(Vdbe *p){
000662 sqlite3VdbeAddOp2(p, OP_Expire, 1, 1);
000663 }
000664
000665 /*
000666 ** Mark the VDBE as one that can be run multiple times.
000667 */
000668 void sqlite3VdbeReusable(Vdbe *p){
000669 int i;
000670 for(i=1; ALWAYS(i<p->nOp); i++){
000671 if( ALWAYS(p->aOp[i].opcode==OP_Expire) ){
000672 p->aOp[1].opcode = OP_Noop;
000673 break;
000674 }
000675 }
000676 }
000677
000678 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
000679
000680 /*
000681 ** The following type and function are used to iterate through all opcodes
000682 ** in a Vdbe main program and each of the sub-programs (triggers) it may
000683 ** invoke directly or indirectly. It should be used as follows:
000684 **
000685 ** Op *pOp;
000686 ** VdbeOpIter sIter;
000687 **
000688 ** memset(&sIter, 0, sizeof(sIter));
000689 ** sIter.v = v; // v is of type Vdbe*
000690 ** while( (pOp = opIterNext(&sIter)) ){
000691 ** // Do something with pOp
000692 ** }
000693 ** sqlite3DbFree(v->db, sIter.apSub);
000694 **
000695 */
000696 typedef struct VdbeOpIter VdbeOpIter;
000697 struct VdbeOpIter {
000698 Vdbe *v; /* Vdbe to iterate through the opcodes of */
000699 SubProgram **apSub; /* Array of subprograms */
000700 int nSub; /* Number of entries in apSub */
000701 int iAddr; /* Address of next instruction to return */
000702 int iSub; /* 0 = main program, 1 = first sub-program etc. */
000703 };
000704 static Op *opIterNext(VdbeOpIter *p){
000705 Vdbe *v = p->v;
000706 Op *pRet = 0;
000707 Op *aOp;
000708 int nOp;
000709
000710 if( p->iSub<=p->nSub ){
000711
000712 if( p->iSub==0 ){
000713 aOp = v->aOp;
000714 nOp = v->nOp;
000715 }else{
000716 aOp = p->apSub[p->iSub-1]->aOp;
000717 nOp = p->apSub[p->iSub-1]->nOp;
000718 }
000719 assert( p->iAddr<nOp );
000720
000721 pRet = &aOp[p->iAddr];
000722 p->iAddr++;
000723 if( p->iAddr==nOp ){
000724 p->iSub++;
000725 p->iAddr = 0;
000726 }
000727
000728 if( pRet->p4type==P4_SUBPROGRAM ){
000729 int nByte = (p->nSub+1)*sizeof(SubProgram*);
000730 int j;
000731 for(j=0; j<p->nSub; j++){
000732 if( p->apSub[j]==pRet->p4.pProgram ) break;
000733 }
000734 if( j==p->nSub ){
000735 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
000736 if( !p->apSub ){
000737 pRet = 0;
000738 }else{
000739 p->apSub[p->nSub++] = pRet->p4.pProgram;
000740 }
000741 }
000742 }
000743 }
000744
000745 return pRet;
000746 }
000747
000748 /*
000749 ** Check if the program stored in the VM associated with pParse may
000750 ** throw an ABORT exception (causing the statement, but not entire transaction
000751 ** to be rolled back). This condition is true if the main program or any
000752 ** sub-programs contains any of the following:
000753 **
000754 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
000755 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
000756 ** * OP_Destroy
000757 ** * OP_VUpdate
000758 ** * OP_VCreate
000759 ** * OP_VRename
000760 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
000761 ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
000762 ** (for CREATE TABLE AS SELECT ...)
000763 **
000764 ** Then check that the value of Parse.mayAbort is true if an
000765 ** ABORT may be thrown, or false otherwise. Return true if it does
000766 ** match, or false otherwise. This function is intended to be used as
000767 ** part of an assert statement in the compiler. Similar to:
000768 **
000769 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
000770 */
000771 int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
000772 int hasAbort = 0;
000773 int hasFkCounter = 0;
000774 int hasCreateTable = 0;
000775 int hasCreateIndex = 0;
000776 int hasInitCoroutine = 0;
000777 Op *pOp;
000778 VdbeOpIter sIter;
000779
000780 if( v==0 ) return 0;
000781 memset(&sIter, 0, sizeof(sIter));
000782 sIter.v = v;
000783
000784 while( (pOp = opIterNext(&sIter))!=0 ){
000785 int opcode = pOp->opcode;
000786 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
000787 || opcode==OP_VDestroy
000788 || opcode==OP_VCreate
000789 || opcode==OP_ParseSchema
000790 || opcode==OP_Function || opcode==OP_PureFunc
000791 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
000792 && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
000793 ){
000794 hasAbort = 1;
000795 break;
000796 }
000797 if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
000798 if( mayAbort ){
000799 /* hasCreateIndex may also be set for some DELETE statements that use
000800 ** OP_Clear. So this routine may end up returning true in the case
000801 ** where a "DELETE FROM tbl" has a statement-journal but does not
000802 ** require one. This is not so bad - it is an inefficiency, not a bug. */
000803 if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
000804 if( opcode==OP_Clear ) hasCreateIndex = 1;
000805 }
000806 if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
000807 #ifndef SQLITE_OMIT_FOREIGN_KEY
000808 if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
000809 hasFkCounter = 1;
000810 }
000811 #endif
000812 }
000813 sqlite3DbFree(v->db, sIter.apSub);
000814
000815 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
000816 ** If malloc failed, then the while() loop above may not have iterated
000817 ** through all opcodes and hasAbort may be set incorrectly. Return
000818 ** true for this case to prevent the assert() in the callers frame
000819 ** from failing. */
000820 return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
000821 || (hasCreateTable && hasInitCoroutine) || hasCreateIndex
000822 );
000823 }
000824 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
000825
000826 #ifdef SQLITE_DEBUG
000827 /*
000828 ** Increment the nWrite counter in the VDBE if the cursor is not an
000829 ** ephemeral cursor, or if the cursor argument is NULL.
000830 */
000831 void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
000832 if( pC==0
000833 || (pC->eCurType!=CURTYPE_SORTER
000834 && pC->eCurType!=CURTYPE_PSEUDO
000835 && !pC->isEphemeral)
000836 ){
000837 p->nWrite++;
000838 }
000839 }
000840 #endif
000841
000842 #ifdef SQLITE_DEBUG
000843 /*
000844 ** Assert if an Abort at this point in time might result in a corrupt
000845 ** database.
000846 */
000847 void sqlite3VdbeAssertAbortable(Vdbe *p){
000848 assert( p->nWrite==0 || p->usesStmtJournal );
000849 }
000850 #endif
000851
000852 /*
000853 ** This routine is called after all opcodes have been inserted. It loops
000854 ** through all the opcodes and fixes up some details.
000855 **
000856 ** (1) For each jump instruction with a negative P2 value (a label)
000857 ** resolve the P2 value to an actual address.
000858 **
000859 ** (2) Compute the maximum number of arguments used by any SQL function
000860 ** and store that value in *pMaxFuncArgs.
000861 **
000862 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
000863 ** indicate what the prepared statement actually does.
000864 **
000865 ** (4) (discontinued)
000866 **
000867 ** (5) Reclaim the memory allocated for storing labels.
000868 **
000869 ** This routine will only function correctly if the mkopcodeh.tcl generator
000870 ** script numbers the opcodes correctly. Changes to this routine must be
000871 ** coordinated with changes to mkopcodeh.tcl.
000872 */
000873 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
000874 int nMaxArgs = *pMaxFuncArgs;
000875 Op *pOp;
000876 Parse *pParse = p->pParse;
000877 int *aLabel = pParse->aLabel;
000878
000879 assert( pParse->db->mallocFailed==0 ); /* tag-20230419-1 */
000880 p->readOnly = 1;
000881 p->bIsReader = 0;
000882 pOp = &p->aOp[p->nOp-1];
000883 assert( p->aOp[0].opcode==OP_Init );
000884 while( 1 /* Loop terminates when it reaches the OP_Init opcode */ ){
000885 /* Only JUMP opcodes and the short list of special opcodes in the switch
000886 ** below need to be considered. The mkopcodeh.tcl generator script groups
000887 ** all these opcodes together near the front of the opcode list. Skip
000888 ** any opcode that does not need processing by virtual of the fact that
000889 ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
000890 */
000891 if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
000892 /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
000893 ** cases from this switch! */
000894 switch( pOp->opcode ){
000895 case OP_Transaction: {
000896 if( pOp->p2!=0 ) p->readOnly = 0;
000897 /* no break */ deliberate_fall_through
000898 }
000899 case OP_AutoCommit:
000900 case OP_Savepoint: {
000901 p->bIsReader = 1;
000902 break;
000903 }
000904 #ifndef SQLITE_OMIT_WAL
000905 case OP_Checkpoint:
000906 #endif
000907 case OP_Vacuum:
000908 case OP_JournalMode: {
000909 p->readOnly = 0;
000910 p->bIsReader = 1;
000911 break;
000912 }
000913 case OP_Init: {
000914 assert( pOp->p2>=0 );
000915 goto resolve_p2_values_loop_exit;
000916 }
000917 #ifndef SQLITE_OMIT_VIRTUALTABLE
000918 case OP_VUpdate: {
000919 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
000920 break;
000921 }
000922 case OP_VFilter: {
000923 int n;
000924 assert( (pOp - p->aOp) >= 3 );
000925 assert( pOp[-1].opcode==OP_Integer );
000926 n = pOp[-1].p1;
000927 if( n>nMaxArgs ) nMaxArgs = n;
000928 /* Fall through into the default case */
000929 /* no break */ deliberate_fall_through
000930 }
000931 #endif
000932 default: {
000933 if( pOp->p2<0 ){
000934 /* The mkopcodeh.tcl script has so arranged things that the only
000935 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
000936 ** have non-negative values for P2. */
000937 assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
000938 assert( ADDR(pOp->p2)<-pParse->nLabel );
000939 assert( aLabel!=0 ); /* True because of tag-20230419-1 */
000940 pOp->p2 = aLabel[ADDR(pOp->p2)];
000941 }
000942
000943 /* OPFLG_JUMP opcodes never have P2==0, though OPFLG_JUMP0 opcodes
000944 ** might */
000945 assert( pOp->p2>0
000946 || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP0)!=0 );
000947
000948 /* Jumps never go off the end of the bytecode array */
000949 assert( pOp->p2<p->nOp
000950 || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)==0 );
000951 break;
000952 }
000953 }
000954 /* The mkopcodeh.tcl script has so arranged things that the only
000955 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
000956 ** have non-negative values for P2. */
000957 assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
000958 }
000959 assert( pOp>p->aOp );
000960 pOp--;
000961 }
000962 resolve_p2_values_loop_exit:
000963 if( aLabel ){
000964 sqlite3DbNNFreeNN(p->db, pParse->aLabel);
000965 pParse->aLabel = 0;
000966 }
000967 pParse->nLabel = 0;
000968 *pMaxFuncArgs = nMaxArgs;
000969 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
000970 }
000971
000972 #ifdef SQLITE_DEBUG
000973 /*
000974 ** Check to see if a subroutine contains a jump to a location outside of
000975 ** the subroutine. If a jump outside the subroutine is detected, add code
000976 ** that will cause the program to halt with an error message.
000977 **
000978 ** The subroutine consists of opcodes between iFirst and iLast. Jumps to
000979 ** locations within the subroutine are acceptable. iRetReg is a register
000980 ** that contains the return address. Jumps to outside the range of iFirst
000981 ** through iLast are also acceptable as long as the jump destination is
000982 ** an OP_Return to iReturnAddr.
000983 **
000984 ** A jump to an unresolved label means that the jump destination will be
000985 ** beyond the current address. That is normally a jump to an early
000986 ** termination and is consider acceptable.
000987 **
000988 ** This routine only runs during debug builds. The purpose is (of course)
000989 ** to detect invalid escapes out of a subroutine. The OP_Halt opcode
000990 ** is generated rather than an assert() or other error, so that ".eqp full"
000991 ** will still work to show the original bytecode, to aid in debugging.
000992 */
000993 void sqlite3VdbeNoJumpsOutsideSubrtn(
000994 Vdbe *v, /* The byte-code program under construction */
000995 int iFirst, /* First opcode of the subroutine */
000996 int iLast, /* Last opcode of the subroutine */
000997 int iRetReg /* Subroutine return address register */
000998 ){
000999 VdbeOp *pOp;
001000 Parse *pParse;
001001 int i;
001002 sqlite3_str *pErr = 0;
001003 assert( v!=0 );
001004 pParse = v->pParse;
001005 assert( pParse!=0 );
001006 if( pParse->nErr ) return;
001007 assert( iLast>=iFirst );
001008 assert( iLast<v->nOp );
001009 pOp = &v->aOp[iFirst];
001010 for(i=iFirst; i<=iLast; i++, pOp++){
001011 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ){
001012 int iDest = pOp->p2; /* Jump destination */
001013 if( iDest==0 ) continue;
001014 if( pOp->opcode==OP_Gosub ) continue;
001015 if( pOp->p3==20230325 && pOp->opcode==OP_NotNull ){
001016 /* This is a deliberately taken illegal branch. tag-20230325-2 */
001017 continue;
001018 }
001019 if( iDest<0 ){
001020 int j = ADDR(iDest);
001021 assert( j>=0 );
001022 if( j>=-pParse->nLabel || pParse->aLabel[j]<0 ){
001023 continue;
001024 }
001025 iDest = pParse->aLabel[j];
001026 }
001027 if( iDest<iFirst || iDest>iLast ){
001028 int j = iDest;
001029 for(; j<v->nOp; j++){
001030 VdbeOp *pX = &v->aOp[j];
001031 if( pX->opcode==OP_Return ){
001032 if( pX->p1==iRetReg ) break;
001033 continue;
001034 }
001035 if( pX->opcode==OP_Noop ) continue;
001036 if( pX->opcode==OP_Explain ) continue;
001037 if( pErr==0 ){
001038 pErr = sqlite3_str_new(0);
001039 }else{
001040 sqlite3_str_appendchar(pErr, 1, '\n');
001041 }
001042 sqlite3_str_appendf(pErr,
001043 "Opcode at %d jumps to %d which is outside the "
001044 "subroutine at %d..%d",
001045 i, iDest, iFirst, iLast);
001046 break;
001047 }
001048 }
001049 }
001050 }
001051 if( pErr ){
001052 char *zErr = sqlite3_str_finish(pErr);
001053 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_INTERNAL, OE_Abort, 0, zErr, 0);
001054 sqlite3_free(zErr);
001055 sqlite3MayAbort(pParse);
001056 }
001057 }
001058 #endif /* SQLITE_DEBUG */
001059
001060 /*
001061 ** Return the address of the next instruction to be inserted.
001062 */
001063 int sqlite3VdbeCurrentAddr(Vdbe *p){
001064 assert( p->eVdbeState==VDBE_INIT_STATE );
001065 return p->nOp;
001066 }
001067
001068 /*
001069 ** Verify that at least N opcode slots are available in p without
001070 ** having to malloc for more space (except when compiled using
001071 ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
001072 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
001073 ** fail due to a OOM fault and hence that the return value from
001074 ** sqlite3VdbeAddOpList() will always be non-NULL.
001075 */
001076 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
001077 void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
001078 assert( p->nOp + N <= p->nOpAlloc );
001079 }
001080 #endif
001081
001082 /*
001083 ** Verify that the VM passed as the only argument does not contain
001084 ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
001085 ** by code in pragma.c to ensure that the implementation of certain
001086 ** pragmas comports with the flags specified in the mkpragmatab.tcl
001087 ** script.
001088 */
001089 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
001090 void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
001091 int i;
001092 for(i=0; i<p->nOp; i++){
001093 assert( p->aOp[i].opcode!=OP_ResultRow );
001094 }
001095 }
001096 #endif
001097
001098 /*
001099 ** Generate code (a single OP_Abortable opcode) that will
001100 ** verify that the VDBE program can safely call Abort in the current
001101 ** context.
001102 */
001103 #if defined(SQLITE_DEBUG)
001104 void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
001105 if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
001106 }
001107 #endif
001108
001109 /*
001110 ** This function returns a pointer to the array of opcodes associated with
001111 ** the Vdbe passed as the first argument. It is the callers responsibility
001112 ** to arrange for the returned array to be eventually freed using the
001113 ** vdbeFreeOpArray() function.
001114 **
001115 ** Before returning, *pnOp is set to the number of entries in the returned
001116 ** array. Also, *pnMaxArg is set to the larger of its current value and
001117 ** the number of entries in the Vdbe.apArg[] array required to execute the
001118 ** returned program.
001119 */
001120 VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
001121 VdbeOp *aOp = p->aOp;
001122 assert( aOp && !p->db->mallocFailed );
001123
001124 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
001125 assert( DbMaskAllZero(p->btreeMask) );
001126
001127 resolveP2Values(p, pnMaxArg);
001128 *pnOp = p->nOp;
001129 p->aOp = 0;
001130 return aOp;
001131 }
001132
001133 /*
001134 ** Add a whole list of operations to the operation stack. Return a
001135 ** pointer to the first operation inserted.
001136 **
001137 ** Non-zero P2 arguments to jump instructions are automatically adjusted
001138 ** so that the jump target is relative to the first operation inserted.
001139 */
001140 VdbeOp *sqlite3VdbeAddOpList(
001141 Vdbe *p, /* Add opcodes to the prepared statement */
001142 int nOp, /* Number of opcodes to add */
001143 VdbeOpList const *aOp, /* The opcodes to be added */
001144 int iLineno /* Source-file line number of first opcode */
001145 ){
001146 int i;
001147 VdbeOp *pOut, *pFirst;
001148 assert( nOp>0 );
001149 assert( p->eVdbeState==VDBE_INIT_STATE );
001150 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
001151 return 0;
001152 }
001153 pFirst = pOut = &p->aOp[p->nOp];
001154 for(i=0; i<nOp; i++, aOp++, pOut++){
001155 pOut->opcode = aOp->opcode;
001156 pOut->p1 = aOp->p1;
001157 pOut->p2 = aOp->p2;
001158 assert( aOp->p2>=0 );
001159 if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
001160 pOut->p2 += p->nOp;
001161 }
001162 pOut->p3 = aOp->p3;
001163 pOut->p4type = P4_NOTUSED;
001164 pOut->p4.p = 0;
001165 pOut->p5 = 0;
001166 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
001167 pOut->zComment = 0;
001168 #endif
001169 #ifdef SQLITE_VDBE_COVERAGE
001170 pOut->iSrcLine = iLineno+i;
001171 #else
001172 (void)iLineno;
001173 #endif
001174 #ifdef SQLITE_DEBUG
001175 if( p->db->flags & SQLITE_VdbeAddopTrace ){
001176 sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
001177 }
001178 #endif
001179 }
001180 p->nOp += nOp;
001181 return pFirst;
001182 }
001183
001184 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
001185 /*
001186 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
001187 */
001188 void sqlite3VdbeScanStatus(
001189 Vdbe *p, /* VM to add scanstatus() to */
001190 int addrExplain, /* Address of OP_Explain (or 0) */
001191 int addrLoop, /* Address of loop counter */
001192 int addrVisit, /* Address of rows visited counter */
001193 LogEst nEst, /* Estimated number of output rows */
001194 const char *zName /* Name of table or index being scanned */
001195 ){
001196 if( IS_STMT_SCANSTATUS(p->db) ){
001197 sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
001198 ScanStatus *aNew;
001199 aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
001200 if( aNew ){
001201 ScanStatus *pNew = &aNew[p->nScan++];
001202 memset(pNew, 0, sizeof(ScanStatus));
001203 pNew->addrExplain = addrExplain;
001204 pNew->addrLoop = addrLoop;
001205 pNew->addrVisit = addrVisit;
001206 pNew->nEst = nEst;
001207 pNew->zName = sqlite3DbStrDup(p->db, zName);
001208 p->aScan = aNew;
001209 }
001210 }
001211 }
001212
001213 /*
001214 ** Add the range of instructions from addrStart to addrEnd (inclusive) to
001215 ** the set of those corresponding to the sqlite3_stmt_scanstatus() counters
001216 ** associated with the OP_Explain instruction at addrExplain. The
001217 ** sum of the sqlite3Hwtime() values for each of these instructions
001218 ** will be returned for SQLITE_SCANSTAT_NCYCLE requests.
001219 */
001220 void sqlite3VdbeScanStatusRange(
001221 Vdbe *p,
001222 int addrExplain,
001223 int addrStart,
001224 int addrEnd
001225 ){
001226 if( IS_STMT_SCANSTATUS(p->db) ){
001227 ScanStatus *pScan = 0;
001228 int ii;
001229 for(ii=p->nScan-1; ii>=0; ii--){
001230 pScan = &p->aScan[ii];
001231 if( pScan->addrExplain==addrExplain ) break;
001232 pScan = 0;
001233 }
001234 if( pScan ){
001235 if( addrEnd<0 ) addrEnd = sqlite3VdbeCurrentAddr(p)-1;
001236 for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
001237 if( pScan->aAddrRange[ii]==0 ){
001238 pScan->aAddrRange[ii] = addrStart;
001239 pScan->aAddrRange[ii+1] = addrEnd;
001240 break;
001241 }
001242 }
001243 }
001244 }
001245 }
001246
001247 /*
001248 ** Set the addresses for the SQLITE_SCANSTAT_NLOOP and SQLITE_SCANSTAT_NROW
001249 ** counters for the query element associated with the OP_Explain at
001250 ** addrExplain.
001251 */
001252 void sqlite3VdbeScanStatusCounters(
001253 Vdbe *p,
001254 int addrExplain,
001255 int addrLoop,
001256 int addrVisit
001257 ){
001258 if( IS_STMT_SCANSTATUS(p->db) ){
001259 ScanStatus *pScan = 0;
001260 int ii;
001261 for(ii=p->nScan-1; ii>=0; ii--){
001262 pScan = &p->aScan[ii];
001263 if( pScan->addrExplain==addrExplain ) break;
001264 pScan = 0;
001265 }
001266 if( pScan ){
001267 if( addrLoop>0 ) pScan->addrLoop = addrLoop;
001268 if( addrVisit>0 ) pScan->addrVisit = addrVisit;
001269 }
001270 }
001271 }
001272 #endif /* defined(SQLITE_ENABLE_STMT_SCANSTATUS) */
001273
001274
001275 /*
001276 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
001277 ** for a specific instruction.
001278 */
001279 void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
001280 assert( addr>=0 );
001281 sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
001282 }
001283 void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
001284 assert( addr>=0 );
001285 sqlite3VdbeGetOp(p,addr)->p1 = val;
001286 }
001287 void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
001288 assert( addr>=0 || p->db->mallocFailed );
001289 sqlite3VdbeGetOp(p,addr)->p2 = val;
001290 }
001291 void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
001292 assert( addr>=0 );
001293 sqlite3VdbeGetOp(p,addr)->p3 = val;
001294 }
001295 void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
001296 assert( p->nOp>0 || p->db->mallocFailed );
001297 if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
001298 }
001299
001300 /*
001301 ** If the previous opcode is an OP_Column that delivers results
001302 ** into register iDest, then add the OPFLAG_TYPEOFARG flag to that
001303 ** opcode.
001304 */
001305 void sqlite3VdbeTypeofColumn(Vdbe *p, int iDest){
001306 VdbeOp *pOp = sqlite3VdbeGetLastOp(p);
001307 if( pOp->p3==iDest && pOp->opcode==OP_Column ){
001308 pOp->p5 |= OPFLAG_TYPEOFARG;
001309 }
001310 }
001311
001312 /*
001313 ** Change the P2 operand of instruction addr so that it points to
001314 ** the address of the next instruction to be coded.
001315 */
001316 void sqlite3VdbeJumpHere(Vdbe *p, int addr){
001317 sqlite3VdbeChangeP2(p, addr, p->nOp);
001318 }
001319
001320 /*
001321 ** Change the P2 operand of the jump instruction at addr so that
001322 ** the jump lands on the next opcode. Or if the jump instruction was
001323 ** the previous opcode (and is thus a no-op) then simply back up
001324 ** the next instruction counter by one slot so that the jump is
001325 ** overwritten by the next inserted opcode.
001326 **
001327 ** This routine is an optimization of sqlite3VdbeJumpHere() that
001328 ** strives to omit useless byte-code like this:
001329 **
001330 ** 7 Once 0 8 0
001331 ** 8 ...
001332 */
001333 void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){
001334 if( addr==p->nOp-1 ){
001335 assert( p->aOp[addr].opcode==OP_Once
001336 || p->aOp[addr].opcode==OP_If
001337 || p->aOp[addr].opcode==OP_FkIfZero );
001338 assert( p->aOp[addr].p4type==0 );
001339 #ifdef SQLITE_VDBE_COVERAGE
001340 sqlite3VdbeGetLastOp(p)->iSrcLine = 0; /* Erase VdbeCoverage() macros */
001341 #endif
001342 p->nOp--;
001343 }else{
001344 sqlite3VdbeChangeP2(p, addr, p->nOp);
001345 }
001346 }
001347
001348
001349 /*
001350 ** If the input FuncDef structure is ephemeral, then free it. If
001351 ** the FuncDef is not ephemeral, then do nothing.
001352 */
001353 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
001354 assert( db!=0 );
001355 if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
001356 sqlite3DbNNFreeNN(db, pDef);
001357 }
001358 }
001359
001360 /*
001361 ** Delete a P4 value if necessary.
001362 */
001363 static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
001364 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
001365 sqlite3DbNNFreeNN(db, p);
001366 }
001367 static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
001368 assert( db!=0 );
001369 freeEphemeralFunction(db, p->pFunc);
001370 sqlite3DbNNFreeNN(db, p);
001371 }
001372 static void freeP4(sqlite3 *db, int p4type, void *p4){
001373 assert( db );
001374 switch( p4type ){
001375 case P4_FUNCCTX: {
001376 freeP4FuncCtx(db, (sqlite3_context*)p4);
001377 break;
001378 }
001379 case P4_REAL:
001380 case P4_INT64:
001381 case P4_DYNAMIC:
001382 case P4_INTARRAY: {
001383 if( p4 ) sqlite3DbNNFreeNN(db, p4);
001384 break;
001385 }
001386 case P4_KEYINFO: {
001387 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
001388 break;
001389 }
001390 #ifdef SQLITE_ENABLE_CURSOR_HINTS
001391 case P4_EXPR: {
001392 sqlite3ExprDelete(db, (Expr*)p4);
001393 break;
001394 }
001395 #endif
001396 case P4_FUNCDEF: {
001397 freeEphemeralFunction(db, (FuncDef*)p4);
001398 break;
001399 }
001400 case P4_MEM: {
001401 if( db->pnBytesFreed==0 ){
001402 sqlite3ValueFree((sqlite3_value*)p4);
001403 }else{
001404 freeP4Mem(db, (Mem*)p4);
001405 }
001406 break;
001407 }
001408 case P4_VTAB : {
001409 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
001410 break;
001411 }
001412 case P4_TABLEREF: {
001413 if( db->pnBytesFreed==0 ) sqlite3DeleteTable(db, (Table*)p4);
001414 break;
001415 }
001416 case P4_SUBRTNSIG: {
001417 SubrtnSig *pSig = (SubrtnSig*)p4;
001418 sqlite3DbFree(db, pSig->zAff);
001419 sqlite3DbFree(db, pSig);
001420 break;
001421 }
001422 }
001423 }
001424
001425 /*
001426 ** Free the space allocated for aOp and any p4 values allocated for the
001427 ** opcodes contained within. If aOp is not NULL it is assumed to contain
001428 ** nOp entries.
001429 */
001430 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
001431 assert( nOp>=0 );
001432 assert( db!=0 );
001433 if( aOp ){
001434 Op *pOp = &aOp[nOp-1];
001435 while(1){ /* Exit via break */
001436 if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
001437 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
001438 sqlite3DbFree(db, pOp->zComment);
001439 #endif
001440 if( pOp==aOp ) break;
001441 pOp--;
001442 }
001443 sqlite3DbNNFreeNN(db, aOp);
001444 }
001445 }
001446
001447 /*
001448 ** Link the SubProgram object passed as the second argument into the linked
001449 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
001450 ** objects when the VM is no longer required.
001451 */
001452 void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
001453 p->pNext = pVdbe->pProgram;
001454 pVdbe->pProgram = p;
001455 }
001456
001457 /*
001458 ** Return true if the given Vdbe has any SubPrograms.
001459 */
001460 int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
001461 return pVdbe->pProgram!=0;
001462 }
001463
001464 /*
001465 ** Change the opcode at addr into OP_Noop
001466 */
001467 int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
001468 VdbeOp *pOp;
001469 if( p->db->mallocFailed ) return 0;
001470 assert( addr>=0 && addr<p->nOp );
001471 pOp = &p->aOp[addr];
001472 freeP4(p->db, pOp->p4type, pOp->p4.p);
001473 pOp->p4type = P4_NOTUSED;
001474 pOp->p4.z = 0;
001475 pOp->opcode = OP_Noop;
001476 return 1;
001477 }
001478
001479 /*
001480 ** If the last opcode is "op" and it is not a jump destination,
001481 ** then remove it. Return true if and only if an opcode was removed.
001482 */
001483 int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
001484 if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
001485 return sqlite3VdbeChangeToNoop(p, p->nOp-1);
001486 }else{
001487 return 0;
001488 }
001489 }
001490
001491 #ifdef SQLITE_DEBUG
001492 /*
001493 ** Generate an OP_ReleaseReg opcode to indicate that a range of
001494 ** registers, except any identified by mask, are no longer in use.
001495 */
001496 void sqlite3VdbeReleaseRegisters(
001497 Parse *pParse, /* Parsing context */
001498 int iFirst, /* Index of first register to be released */
001499 int N, /* Number of registers to release */
001500 u32 mask, /* Mask of registers to NOT release */
001501 int bUndefine /* If true, mark registers as undefined */
001502 ){
001503 if( N==0 || OptimizationDisabled(pParse->db, SQLITE_ReleaseReg) ) return;
001504 assert( pParse->pVdbe );
001505 assert( iFirst>=1 );
001506 assert( iFirst+N-1<=pParse->nMem );
001507 if( N<=31 && mask!=0 ){
001508 while( N>0 && (mask&1)!=0 ){
001509 mask >>= 1;
001510 iFirst++;
001511 N--;
001512 }
001513 while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
001514 mask &= ~MASKBIT32(N-1);
001515 N--;
001516 }
001517 }
001518 if( N>0 ){
001519 sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
001520 if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
001521 }
001522 }
001523 #endif /* SQLITE_DEBUG */
001524
001525 /*
001526 ** Change the value of the P4 operand for a specific instruction.
001527 ** This routine is useful when a large program is loaded from a
001528 ** static array using sqlite3VdbeAddOpList but we want to make a
001529 ** few minor changes to the program.
001530 **
001531 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
001532 ** the string is made into memory obtained from sqlite3_malloc().
001533 ** A value of n==0 means copy bytes of zP4 up to and including the
001534 ** first null byte. If n>0 then copy n+1 bytes of zP4.
001535 **
001536 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
001537 ** to a string or structure that is guaranteed to exist for the lifetime of
001538 ** the Vdbe. In these cases we can just copy the pointer.
001539 **
001540 ** If addr<0 then change P4 on the most recently inserted instruction.
001541 */
001542 static void SQLITE_NOINLINE vdbeChangeP4Full(
001543 Vdbe *p,
001544 Op *pOp,
001545 const char *zP4,
001546 int n
001547 ){
001548 if( pOp->p4type ){
001549 assert( pOp->p4type > P4_FREE_IF_LE );
001550 pOp->p4type = 0;
001551 pOp->p4.p = 0;
001552 }
001553 if( n<0 ){
001554 sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
001555 }else{
001556 if( n==0 ) n = sqlite3Strlen30(zP4);
001557 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
001558 pOp->p4type = P4_DYNAMIC;
001559 }
001560 }
001561 void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
001562 Op *pOp;
001563 sqlite3 *db;
001564 assert( p!=0 );
001565 db = p->db;
001566 assert( p->eVdbeState==VDBE_INIT_STATE );
001567 assert( p->aOp!=0 || db->mallocFailed );
001568 if( db->mallocFailed ){
001569 if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
001570 return;
001571 }
001572 assert( p->nOp>0 );
001573 assert( addr<p->nOp );
001574 if( addr<0 ){
001575 addr = p->nOp - 1;
001576 }
001577 pOp = &p->aOp[addr];
001578 if( n>=0 || pOp->p4type ){
001579 vdbeChangeP4Full(p, pOp, zP4, n);
001580 return;
001581 }
001582 if( n==P4_INT32 ){
001583 /* Note: this cast is safe, because the origin data point was an int
001584 ** that was cast to a (const char *). */
001585 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
001586 pOp->p4type = P4_INT32;
001587 }else if( zP4!=0 ){
001588 assert( n<0 );
001589 pOp->p4.p = (void*)zP4;
001590 pOp->p4type = (signed char)n;
001591 if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
001592 }
001593 }
001594
001595 /*
001596 ** Change the P4 operand of the most recently coded instruction
001597 ** to the value defined by the arguments. This is a high-speed
001598 ** version of sqlite3VdbeChangeP4().
001599 **
001600 ** The P4 operand must not have been previously defined. And the new
001601 ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
001602 ** those cases.
001603 */
001604 void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
001605 VdbeOp *pOp;
001606 assert( n!=P4_INT32 && n!=P4_VTAB );
001607 assert( n<=0 );
001608 if( p->db->mallocFailed ){
001609 freeP4(p->db, n, pP4);
001610 }else{
001611 assert( pP4!=0 || n==P4_DYNAMIC );
001612 assert( p->nOp>0 );
001613 pOp = &p->aOp[p->nOp-1];
001614 assert( pOp->p4type==P4_NOTUSED );
001615 pOp->p4type = n;
001616 pOp->p4.p = pP4;
001617 }
001618 }
001619
001620 /*
001621 ** Set the P4 on the most recently added opcode to the KeyInfo for the
001622 ** index given.
001623 */
001624 void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
001625 Vdbe *v = pParse->pVdbe;
001626 KeyInfo *pKeyInfo;
001627 assert( v!=0 );
001628 assert( pIdx!=0 );
001629 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
001630 if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
001631 }
001632
001633 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
001634 /*
001635 ** Change the comment on the most recently coded instruction. Or
001636 ** insert a No-op and add the comment to that new instruction. This
001637 ** makes the code easier to read during debugging. None of this happens
001638 ** in a production build.
001639 */
001640 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
001641 assert( p->nOp>0 || p->aOp==0 );
001642 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->pParse->nErr>0 );
001643 if( p->nOp ){
001644 assert( p->aOp );
001645 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
001646 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
001647 }
001648 }
001649 void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
001650 va_list ap;
001651 if( p ){
001652 va_start(ap, zFormat);
001653 vdbeVComment(p, zFormat, ap);
001654 va_end(ap);
001655 }
001656 }
001657 void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
001658 va_list ap;
001659 if( p ){
001660 sqlite3VdbeAddOp0(p, OP_Noop);
001661 va_start(ap, zFormat);
001662 vdbeVComment(p, zFormat, ap);
001663 va_end(ap);
001664 }
001665 }
001666 #endif /* NDEBUG */
001667
001668 #ifdef SQLITE_VDBE_COVERAGE
001669 /*
001670 ** Set the value if the iSrcLine field for the previously coded instruction.
001671 */
001672 void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
001673 sqlite3VdbeGetLastOp(v)->iSrcLine = iLine;
001674 }
001675 #endif /* SQLITE_VDBE_COVERAGE */
001676
001677 /*
001678 ** Return the opcode for a given address. The address must be non-negative.
001679 ** See sqlite3VdbeGetLastOp() to get the most recently added opcode.
001680 **
001681 ** If a memory allocation error has occurred prior to the calling of this
001682 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
001683 ** is readable but not writable, though it is cast to a writable value.
001684 ** The return of a dummy opcode allows the call to continue functioning
001685 ** after an OOM fault without having to check to see if the return from
001686 ** this routine is a valid pointer. But because the dummy.opcode is 0,
001687 ** dummy will never be written to. This is verified by code inspection and
001688 ** by running with Valgrind.
001689 */
001690 VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
001691 /* C89 specifies that the constant "dummy" will be initialized to all
001692 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
001693 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
001694 assert( p->eVdbeState==VDBE_INIT_STATE );
001695 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
001696 if( p->db->mallocFailed ){
001697 return (VdbeOp*)&dummy;
001698 }else{
001699 return &p->aOp[addr];
001700 }
001701 }
001702
001703 /* Return the most recently added opcode
001704 */
001705 VdbeOp *sqlite3VdbeGetLastOp(Vdbe *p){
001706 return sqlite3VdbeGetOp(p, p->nOp - 1);
001707 }
001708
001709 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
001710 /*
001711 ** Return an integer value for one of the parameters to the opcode pOp
001712 ** determined by character c.
001713 */
001714 static int translateP(char c, const Op *pOp){
001715 if( c=='1' ) return pOp->p1;
001716 if( c=='2' ) return pOp->p2;
001717 if( c=='3' ) return pOp->p3;
001718 if( c=='4' ) return pOp->p4.i;
001719 return pOp->p5;
001720 }
001721
001722 /*
001723 ** Compute a string for the "comment" field of a VDBE opcode listing.
001724 **
001725 ** The Synopsis: field in comments in the vdbe.c source file gets converted
001726 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
001727 ** absence of other comments, this synopsis becomes the comment on the opcode.
001728 ** Some translation occurs:
001729 **
001730 ** "PX" -> "r[X]"
001731 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
001732 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
001733 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
001734 */
001735 char *sqlite3VdbeDisplayComment(
001736 sqlite3 *db, /* Optional - Oom error reporting only */
001737 const Op *pOp, /* The opcode to be commented */
001738 const char *zP4 /* Previously obtained value for P4 */
001739 ){
001740 const char *zOpName;
001741 const char *zSynopsis;
001742 int nOpName;
001743 int ii;
001744 char zAlt[50];
001745 StrAccum x;
001746
001747 sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
001748 zOpName = sqlite3OpcodeName(pOp->opcode);
001749 nOpName = sqlite3Strlen30(zOpName);
001750 if( zOpName[nOpName+1] ){
001751 int seenCom = 0;
001752 char c;
001753 zSynopsis = zOpName + nOpName + 1;
001754 if( strncmp(zSynopsis,"IF ",3)==0 ){
001755 sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
001756 zSynopsis = zAlt;
001757 }
001758 for(ii=0; (c = zSynopsis[ii])!=0; ii++){
001759 if( c=='P' ){
001760 c = zSynopsis[++ii];
001761 if( c=='4' ){
001762 sqlite3_str_appendall(&x, zP4);
001763 }else if( c=='X' ){
001764 if( pOp->zComment && pOp->zComment[0] ){
001765 sqlite3_str_appendall(&x, pOp->zComment);
001766 seenCom = 1;
001767 break;
001768 }
001769 }else{
001770 int v1 = translateP(c, pOp);
001771 int v2;
001772 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
001773 ii += 3;
001774 v2 = translateP(zSynopsis[ii], pOp);
001775 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
001776 ii += 2;
001777 v2++;
001778 }
001779 if( v2<2 ){
001780 sqlite3_str_appendf(&x, "%d", v1);
001781 }else{
001782 sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
001783 }
001784 }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){
001785 sqlite3_context *pCtx = pOp->p4.pCtx;
001786 if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
001787 sqlite3_str_appendf(&x, "%d", v1);
001788 }else if( pCtx->argc>1 ){
001789 sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
001790 }else if( x.accError==0 ){
001791 assert( x.nChar>2 );
001792 x.nChar -= 2;
001793 ii++;
001794 }
001795 ii += 3;
001796 }else{
001797 sqlite3_str_appendf(&x, "%d", v1);
001798 if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
001799 ii += 4;
001800 }
001801 }
001802 }
001803 }else{
001804 sqlite3_str_appendchar(&x, 1, c);
001805 }
001806 }
001807 if( !seenCom && pOp->zComment ){
001808 sqlite3_str_appendf(&x, "; %s", pOp->zComment);
001809 }
001810 }else if( pOp->zComment ){
001811 sqlite3_str_appendall(&x, pOp->zComment);
001812 }
001813 if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){
001814 sqlite3OomFault(db);
001815 }
001816 return sqlite3StrAccumFinish(&x);
001817 }
001818 #endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */
001819
001820 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
001821 /*
001822 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
001823 ** that can be displayed in the P4 column of EXPLAIN output.
001824 */
001825 static void displayP4Expr(StrAccum *p, Expr *pExpr){
001826 const char *zOp = 0;
001827 switch( pExpr->op ){
001828 case TK_STRING:
001829 assert( !ExprHasProperty(pExpr, EP_IntValue) );
001830 sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
001831 break;
001832 case TK_INTEGER:
001833 sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
001834 break;
001835 case TK_NULL:
001836 sqlite3_str_appendf(p, "NULL");
001837 break;
001838 case TK_REGISTER: {
001839 sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
001840 break;
001841 }
001842 case TK_COLUMN: {
001843 if( pExpr->iColumn<0 ){
001844 sqlite3_str_appendf(p, "rowid");
001845 }else{
001846 sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
001847 }
001848 break;
001849 }
001850 case TK_LT: zOp = "LT"; break;
001851 case TK_LE: zOp = "LE"; break;
001852 case TK_GT: zOp = "GT"; break;
001853 case TK_GE: zOp = "GE"; break;
001854 case TK_NE: zOp = "NE"; break;
001855 case TK_EQ: zOp = "EQ"; break;
001856 case TK_IS: zOp = "IS"; break;
001857 case TK_ISNOT: zOp = "ISNOT"; break;
001858 case TK_AND: zOp = "AND"; break;
001859 case TK_OR: zOp = "OR"; break;
001860 case TK_PLUS: zOp = "ADD"; break;
001861 case TK_STAR: zOp = "MUL"; break;
001862 case TK_MINUS: zOp = "SUB"; break;
001863 case TK_REM: zOp = "REM"; break;
001864 case TK_BITAND: zOp = "BITAND"; break;
001865 case TK_BITOR: zOp = "BITOR"; break;
001866 case TK_SLASH: zOp = "DIV"; break;
001867 case TK_LSHIFT: zOp = "LSHIFT"; break;
001868 case TK_RSHIFT: zOp = "RSHIFT"; break;
001869 case TK_CONCAT: zOp = "CONCAT"; break;
001870 case TK_UMINUS: zOp = "MINUS"; break;
001871 case TK_UPLUS: zOp = "PLUS"; break;
001872 case TK_BITNOT: zOp = "BITNOT"; break;
001873 case TK_NOT: zOp = "NOT"; break;
001874 case TK_ISNULL: zOp = "ISNULL"; break;
001875 case TK_NOTNULL: zOp = "NOTNULL"; break;
001876
001877 default:
001878 sqlite3_str_appendf(p, "%s", "expr");
001879 break;
001880 }
001881
001882 if( zOp ){
001883 sqlite3_str_appendf(p, "%s(", zOp);
001884 displayP4Expr(p, pExpr->pLeft);
001885 if( pExpr->pRight ){
001886 sqlite3_str_append(p, ",", 1);
001887 displayP4Expr(p, pExpr->pRight);
001888 }
001889 sqlite3_str_append(p, ")", 1);
001890 }
001891 }
001892 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
001893
001894
001895 #if VDBE_DISPLAY_P4
001896 /*
001897 ** Compute a string that describes the P4 parameter for an opcode.
001898 ** Use zTemp for any required temporary buffer space.
001899 */
001900 char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
001901 char *zP4 = 0;
001902 StrAccum x;
001903
001904 sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
001905 switch( pOp->p4type ){
001906 case P4_KEYINFO: {
001907 int j;
001908 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
001909 assert( pKeyInfo->aSortFlags!=0 );
001910 sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
001911 for(j=0; j<pKeyInfo->nKeyField; j++){
001912 CollSeq *pColl = pKeyInfo->aColl[j];
001913 const char *zColl = pColl ? pColl->zName : "";
001914 if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
001915 sqlite3_str_appendf(&x, ",%s%s%s",
001916 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
001917 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
001918 zColl);
001919 }
001920 sqlite3_str_append(&x, ")", 1);
001921 break;
001922 }
001923 #ifdef SQLITE_ENABLE_CURSOR_HINTS
001924 case P4_EXPR: {
001925 displayP4Expr(&x, pOp->p4.pExpr);
001926 break;
001927 }
001928 #endif
001929 case P4_COLLSEQ: {
001930 static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
001931 CollSeq *pColl = pOp->p4.pColl;
001932 assert( pColl->enc<4 );
001933 sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
001934 encnames[pColl->enc]);
001935 break;
001936 }
001937 case P4_FUNCDEF: {
001938 FuncDef *pDef = pOp->p4.pFunc;
001939 sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
001940 break;
001941 }
001942 case P4_FUNCCTX: {
001943 FuncDef *pDef = pOp->p4.pCtx->pFunc;
001944 sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
001945 break;
001946 }
001947 case P4_INT64: {
001948 sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
001949 break;
001950 }
001951 case P4_INT32: {
001952 sqlite3_str_appendf(&x, "%d", pOp->p4.i);
001953 break;
001954 }
001955 case P4_REAL: {
001956 sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
001957 break;
001958 }
001959 case P4_MEM: {
001960 Mem *pMem = pOp->p4.pMem;
001961 if( pMem->flags & MEM_Str ){
001962 zP4 = pMem->z;
001963 }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
001964 sqlite3_str_appendf(&x, "%lld", pMem->u.i);
001965 }else if( pMem->flags & MEM_Real ){
001966 sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
001967 }else if( pMem->flags & MEM_Null ){
001968 zP4 = "NULL";
001969 }else{
001970 assert( pMem->flags & MEM_Blob );
001971 zP4 = "(blob)";
001972 }
001973 break;
001974 }
001975 #ifndef SQLITE_OMIT_VIRTUALTABLE
001976 case P4_VTAB: {
001977 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
001978 sqlite3_str_appendf(&x, "vtab:%p", pVtab);
001979 break;
001980 }
001981 #endif
001982 case P4_INTARRAY: {
001983 u32 i;
001984 u32 *ai = pOp->p4.ai;
001985 u32 n = ai[0]; /* The first element of an INTARRAY is always the
001986 ** count of the number of elements to follow */
001987 for(i=1; i<=n; i++){
001988 sqlite3_str_appendf(&x, "%c%u", (i==1 ? '[' : ','), ai[i]);
001989 }
001990 sqlite3_str_append(&x, "]", 1);
001991 break;
001992 }
001993 case P4_SUBPROGRAM: {
001994 zP4 = "program";
001995 break;
001996 }
001997 case P4_TABLE: {
001998 zP4 = pOp->p4.pTab->zName;
001999 break;
002000 }
002001 case P4_SUBRTNSIG: {
002002 SubrtnSig *pSig = pOp->p4.pSubrtnSig;
002003 sqlite3_str_appendf(&x, "subrtnsig:%d,%s", pSig->selId, pSig->zAff);
002004 break;
002005 }
002006 default: {
002007 zP4 = pOp->p4.z;
002008 }
002009 }
002010 if( zP4 ) sqlite3_str_appendall(&x, zP4);
002011 if( (x.accError & SQLITE_NOMEM)!=0 ){
002012 sqlite3OomFault(db);
002013 }
002014 return sqlite3StrAccumFinish(&x);
002015 }
002016 #endif /* VDBE_DISPLAY_P4 */
002017
002018 /*
002019 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
002020 **
002021 ** The prepared statements need to know in advance the complete set of
002022 ** attached databases that will be use. A mask of these databases
002023 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
002024 ** p->btreeMask of databases that will require a lock.
002025 */
002026 void sqlite3VdbeUsesBtree(Vdbe *p, int i){
002027 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
002028 assert( i<(int)sizeof(p->btreeMask)*8 );
002029 DbMaskSet(p->btreeMask, i);
002030 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
002031 DbMaskSet(p->lockMask, i);
002032 }
002033 }
002034
002035 #if !defined(SQLITE_OMIT_SHARED_CACHE)
002036 /*
002037 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
002038 ** this routine obtains the mutex associated with each BtShared structure
002039 ** that may be accessed by the VM passed as an argument. In doing so it also
002040 ** sets the BtShared.db member of each of the BtShared structures, ensuring
002041 ** that the correct busy-handler callback is invoked if required.
002042 **
002043 ** If SQLite is not threadsafe but does support shared-cache mode, then
002044 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
002045 ** of all of BtShared structures accessible via the database handle
002046 ** associated with the VM.
002047 **
002048 ** If SQLite is not threadsafe and does not support shared-cache mode, this
002049 ** function is a no-op.
002050 **
002051 ** The p->btreeMask field is a bitmask of all btrees that the prepared
002052 ** statement p will ever use. Let N be the number of bits in p->btreeMask
002053 ** corresponding to btrees that use shared cache. Then the runtime of
002054 ** this routine is N*N. But as N is rarely more than 1, this should not
002055 ** be a problem.
002056 */
002057 void sqlite3VdbeEnter(Vdbe *p){
002058 int i;
002059 sqlite3 *db;
002060 Db *aDb;
002061 int nDb;
002062 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
002063 db = p->db;
002064 aDb = db->aDb;
002065 nDb = db->nDb;
002066 for(i=0; i<nDb; i++){
002067 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
002068 sqlite3BtreeEnter(aDb[i].pBt);
002069 }
002070 }
002071 }
002072 #endif
002073
002074 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
002075 /*
002076 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
002077 */
002078 static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
002079 int i;
002080 sqlite3 *db;
002081 Db *aDb;
002082 int nDb;
002083 db = p->db;
002084 aDb = db->aDb;
002085 nDb = db->nDb;
002086 for(i=0; i<nDb; i++){
002087 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
002088 sqlite3BtreeLeave(aDb[i].pBt);
002089 }
002090 }
002091 }
002092 void sqlite3VdbeLeave(Vdbe *p){
002093 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
002094 vdbeLeave(p);
002095 }
002096 #endif
002097
002098 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
002099 /*
002100 ** Print a single opcode. This routine is used for debugging only.
002101 */
002102 void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
002103 char *zP4;
002104 char *zCom;
002105 sqlite3 dummyDb;
002106 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
002107 if( pOut==0 ) pOut = stdout;
002108 sqlite3BeginBenignMalloc();
002109 dummyDb.mallocFailed = 1;
002110 zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);
002111 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
002112 zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);
002113 #else
002114 zCom = 0;
002115 #endif
002116 /* NB: The sqlite3OpcodeName() function is implemented by code created
002117 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
002118 ** information from the vdbe.c source text */
002119 fprintf(pOut, zFormat1, pc,
002120 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
002121 zP4 ? zP4 : "", pOp->p5,
002122 zCom ? zCom : ""
002123 );
002124 fflush(pOut);
002125 sqlite3_free(zP4);
002126 sqlite3_free(zCom);
002127 sqlite3EndBenignMalloc();
002128 }
002129 #endif
002130
002131 /*
002132 ** Initialize an array of N Mem element.
002133 **
002134 ** This is a high-runner, so only those fields that really do need to
002135 ** be initialized are set. The Mem structure is organized so that
002136 ** the fields that get initialized are nearby and hopefully on the same
002137 ** cache line.
002138 **
002139 ** Mem.flags = flags
002140 ** Mem.db = db
002141 ** Mem.szMalloc = 0
002142 **
002143 ** All other fields of Mem can safely remain uninitialized for now. They
002144 ** will be initialized before use.
002145 */
002146 static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
002147 assert( db!=0 );
002148 if( N>0 ){
002149 do{
002150 p->flags = flags;
002151 p->db = db;
002152 p->szMalloc = 0;
002153 #ifdef SQLITE_DEBUG
002154 p->pScopyFrom = 0;
002155 p->bScopy = 0;
002156 #endif
002157 p++;
002158 }while( (--N)>0 );
002159 }
002160 }
002161
002162 /*
002163 ** Release auxiliary memory held in an array of N Mem elements.
002164 **
002165 ** After this routine returns, all Mem elements in the array will still
002166 ** be valid. Those Mem elements that were not holding auxiliary resources
002167 ** will be unchanged. Mem elements which had something freed will be
002168 ** set to MEM_Undefined.
002169 */
002170 static void releaseMemArray(Mem *p, int N){
002171 if( p && N ){
002172 Mem *pEnd = &p[N];
002173 sqlite3 *db = p->db;
002174 assert( db!=0 );
002175 if( db->pnBytesFreed ){
002176 do{
002177 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
002178 }while( (++p)<pEnd );
002179 return;
002180 }
002181 do{
002182 assert( (&p[1])==pEnd || p[0].db==p[1].db );
002183 assert( sqlite3VdbeCheckMemInvariants(p) );
002184
002185 /* This block is really an inlined version of sqlite3VdbeMemRelease()
002186 ** that takes advantage of the fact that the memory cell value is
002187 ** being set to NULL after releasing any dynamic resources.
002188 **
002189 ** The justification for duplicating code is that according to
002190 ** callgrind, this causes a certain test case to hit the CPU 4.7
002191 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
002192 ** sqlite3MemRelease() were called from here. With -O2, this jumps
002193 ** to 6.6 percent. The test case is inserting 1000 rows into a table
002194 ** with no indexes using a single prepared INSERT statement, bind()
002195 ** and reset(). Inserts are grouped into a transaction.
002196 */
002197 testcase( p->flags & MEM_Agg );
002198 testcase( p->flags & MEM_Dyn );
002199 if( p->flags&(MEM_Agg|MEM_Dyn) ){
002200 testcase( (p->flags & MEM_Dyn)!=0 && p->xDel==sqlite3VdbeFrameMemDel );
002201 sqlite3VdbeMemRelease(p);
002202 p->flags = MEM_Undefined;
002203 }else if( p->szMalloc ){
002204 sqlite3DbNNFreeNN(db, p->zMalloc);
002205 p->szMalloc = 0;
002206 p->flags = MEM_Undefined;
002207 }
002208 #ifdef SQLITE_DEBUG
002209 else{
002210 p->flags = MEM_Undefined;
002211 }
002212 #endif
002213 }while( (++p)<pEnd );
002214 }
002215 }
002216
002217 #ifdef SQLITE_DEBUG
002218 /*
002219 ** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
002220 ** and false if something is wrong.
002221 **
002222 ** This routine is intended for use inside of assert() statements only.
002223 */
002224 int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
002225 if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
002226 return 1;
002227 }
002228 #endif
002229
002230
002231 /*
002232 ** This is a destructor on a Mem object (which is really an sqlite3_value)
002233 ** that deletes the Frame object that is attached to it as a blob.
002234 **
002235 ** This routine does not delete the Frame right away. It merely adds the
002236 ** frame to a list of frames to be deleted when the Vdbe halts.
002237 */
002238 void sqlite3VdbeFrameMemDel(void *pArg){
002239 VdbeFrame *pFrame = (VdbeFrame*)pArg;
002240 assert( sqlite3VdbeFrameIsValid(pFrame) );
002241 pFrame->pParent = pFrame->v->pDelFrame;
002242 pFrame->v->pDelFrame = pFrame;
002243 }
002244
002245 #if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)
002246 /*
002247 ** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
002248 ** QUERY PLAN output.
002249 **
002250 ** Return SQLITE_ROW on success. Return SQLITE_DONE if there are no
002251 ** more opcodes to be displayed.
002252 */
002253 int sqlite3VdbeNextOpcode(
002254 Vdbe *p, /* The statement being explained */
002255 Mem *pSub, /* Storage for keeping track of subprogram nesting */
002256 int eMode, /* 0: normal. 1: EQP. 2: TablesUsed */
002257 int *piPc, /* IN/OUT: Current rowid. Overwritten with next rowid */
002258 int *piAddr, /* OUT: Write index into (*paOp)[] here */
002259 Op **paOp /* OUT: Write the opcode array here */
002260 ){
002261 int nRow; /* Stop when row count reaches this */
002262 int nSub = 0; /* Number of sub-vdbes seen so far */
002263 SubProgram **apSub = 0; /* Array of sub-vdbes */
002264 int i; /* Next instruction address */
002265 int rc = SQLITE_OK; /* Result code */
002266 Op *aOp = 0; /* Opcode array */
002267 int iPc; /* Rowid. Copy of value in *piPc */
002268
002269 /* When the number of output rows reaches nRow, that means the
002270 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
002271 ** nRow is the sum of the number of rows in the main program, plus
002272 ** the sum of the number of rows in all trigger subprograms encountered
002273 ** so far. The nRow value will increase as new trigger subprograms are
002274 ** encountered, but p->pc will eventually catch up to nRow.
002275 */
002276 nRow = p->nOp;
002277 if( pSub!=0 ){
002278 if( pSub->flags&MEM_Blob ){
002279 /* pSub is initiallly NULL. It is initialized to a BLOB by
002280 ** the P4_SUBPROGRAM processing logic below */
002281 nSub = pSub->n/sizeof(Vdbe*);
002282 apSub = (SubProgram **)pSub->z;
002283 }
002284 for(i=0; i<nSub; i++){
002285 nRow += apSub[i]->nOp;
002286 }
002287 }
002288 iPc = *piPc;
002289 while(1){ /* Loop exits via break */
002290 i = iPc++;
002291 if( i>=nRow ){
002292 p->rc = SQLITE_OK;
002293 rc = SQLITE_DONE;
002294 break;
002295 }
002296 if( i<p->nOp ){
002297 /* The rowid is small enough that we are still in the
002298 ** main program. */
002299 aOp = p->aOp;
002300 }else{
002301 /* We are currently listing subprograms. Figure out which one and
002302 ** pick up the appropriate opcode. */
002303 int j;
002304 i -= p->nOp;
002305 assert( apSub!=0 );
002306 assert( nSub>0 );
002307 for(j=0; i>=apSub[j]->nOp; j++){
002308 i -= apSub[j]->nOp;
002309 assert( i<apSub[j]->nOp || j+1<nSub );
002310 }
002311 aOp = apSub[j]->aOp;
002312 }
002313
002314 /* When an OP_Program opcode is encounter (the only opcode that has
002315 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
002316 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
002317 ** has not already been seen.
002318 */
002319 if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){
002320 int nByte = (nSub+1)*sizeof(SubProgram*);
002321 int j;
002322 for(j=0; j<nSub; j++){
002323 if( apSub[j]==aOp[i].p4.pProgram ) break;
002324 }
002325 if( j==nSub ){
002326 p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
002327 if( p->rc!=SQLITE_OK ){
002328 rc = SQLITE_ERROR;
002329 break;
002330 }
002331 apSub = (SubProgram **)pSub->z;
002332 apSub[nSub++] = aOp[i].p4.pProgram;
002333 MemSetTypeFlag(pSub, MEM_Blob);
002334 pSub->n = nSub*sizeof(SubProgram*);
002335 nRow += aOp[i].p4.pProgram->nOp;
002336 }
002337 }
002338 if( eMode==0 ) break;
002339 #ifdef SQLITE_ENABLE_BYTECODE_VTAB
002340 if( eMode==2 ){
002341 Op *pOp = aOp + i;
002342 if( pOp->opcode==OP_OpenRead ) break;
002343 if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
002344 if( pOp->opcode==OP_ReopenIdx ) break;
002345 }else
002346 #endif
002347 {
002348 assert( eMode==1 );
002349 if( aOp[i].opcode==OP_Explain ) break;
002350 if( aOp[i].opcode==OP_Init && iPc>1 ) break;
002351 }
002352 }
002353 *piPc = iPc;
002354 *piAddr = i;
002355 *paOp = aOp;
002356 return rc;
002357 }
002358 #endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */
002359
002360
002361 /*
002362 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
002363 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
002364 */
002365 void sqlite3VdbeFrameDelete(VdbeFrame *p){
002366 int i;
002367 Mem *aMem = VdbeFrameMem(p);
002368 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
002369 assert( sqlite3VdbeFrameIsValid(p) );
002370 for(i=0; i<p->nChildCsr; i++){
002371 if( apCsr[i] ) sqlite3VdbeFreeCursorNN(p->v, apCsr[i]);
002372 }
002373 releaseMemArray(aMem, p->nChildMem);
002374 sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
002375 sqlite3DbFree(p->v->db, p);
002376 }
002377
002378 #ifndef SQLITE_OMIT_EXPLAIN
002379 /*
002380 ** Give a listing of the program in the virtual machine.
002381 **
002382 ** The interface is the same as sqlite3VdbeExec(). But instead of
002383 ** running the code, it invokes the callback once for each instruction.
002384 ** This feature is used to implement "EXPLAIN".
002385 **
002386 ** When p->explain==1, each instruction is listed. When
002387 ** p->explain==2, only OP_Explain instructions are listed and these
002388 ** are shown in a different format. p->explain==2 is used to implement
002389 ** EXPLAIN QUERY PLAN.
002390 ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
002391 ** are also shown, so that the boundaries between the main program and
002392 ** each trigger are clear.
002393 **
002394 ** When p->explain==1, first the main program is listed, then each of
002395 ** the trigger subprograms are listed one by one.
002396 */
002397 int sqlite3VdbeList(
002398 Vdbe *p /* The VDBE */
002399 ){
002400 Mem *pSub = 0; /* Memory cell hold array of subprogs */
002401 sqlite3 *db = p->db; /* The database connection */
002402 int i; /* Loop counter */
002403 int rc = SQLITE_OK; /* Return code */
002404 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
002405 int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
002406 Op *aOp; /* Array of opcodes */
002407 Op *pOp; /* Current opcode */
002408
002409 assert( p->explain );
002410 assert( p->eVdbeState==VDBE_RUN_STATE );
002411 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
002412
002413 /* Even though this opcode does not use dynamic strings for
002414 ** the result, result columns may become dynamic if the user calls
002415 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
002416 */
002417 releaseMemArray(pMem, 8);
002418
002419 if( p->rc==SQLITE_NOMEM ){
002420 /* This happens if a malloc() inside a call to sqlite3_column_text() or
002421 ** sqlite3_column_text16() failed. */
002422 sqlite3OomFault(db);
002423 return SQLITE_ERROR;
002424 }
002425
002426 if( bListSubprogs ){
002427 /* The first 8 memory cells are used for the result set. So we will
002428 ** commandeer the 9th cell to use as storage for an array of pointers
002429 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
002430 ** cells. */
002431 assert( p->nMem>9 );
002432 pSub = &p->aMem[9];
002433 }else{
002434 pSub = 0;
002435 }
002436
002437 /* Figure out which opcode is next to display */
002438 rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
002439
002440 if( rc==SQLITE_OK ){
002441 pOp = aOp + i;
002442 if( AtomicLoad(&db->u1.isInterrupted) ){
002443 p->rc = SQLITE_INTERRUPT;
002444 rc = SQLITE_ERROR;
002445 sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
002446 }else{
002447 char *zP4 = sqlite3VdbeDisplayP4(db, pOp);
002448 if( p->explain==2 ){
002449 sqlite3VdbeMemSetInt64(pMem, pOp->p1);
002450 sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
002451 sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
002452 sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
002453 assert( p->nResColumn==4 );
002454 }else{
002455 sqlite3VdbeMemSetInt64(pMem+0, i);
002456 sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
002457 -1, SQLITE_UTF8, SQLITE_STATIC);
002458 sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
002459 sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
002460 sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
002461 /* pMem+5 for p4 is done last */
002462 sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
002463 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
002464 {
002465 char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);
002466 sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
002467 }
002468 #else
002469 sqlite3VdbeMemSetNull(pMem+7);
002470 #endif
002471 sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
002472 assert( p->nResColumn==8 );
002473 }
002474 p->pResultRow = pMem;
002475 if( db->mallocFailed ){
002476 p->rc = SQLITE_NOMEM;
002477 rc = SQLITE_ERROR;
002478 }else{
002479 p->rc = SQLITE_OK;
002480 rc = SQLITE_ROW;
002481 }
002482 }
002483 }
002484 return rc;
002485 }
002486 #endif /* SQLITE_OMIT_EXPLAIN */
002487
002488 #ifdef SQLITE_DEBUG
002489 /*
002490 ** Print the SQL that was used to generate a VDBE program.
002491 */
002492 void sqlite3VdbePrintSql(Vdbe *p){
002493 const char *z = 0;
002494 if( p->zSql ){
002495 z = p->zSql;
002496 }else if( p->nOp>=1 ){
002497 const VdbeOp *pOp = &p->aOp[0];
002498 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
002499 z = pOp->p4.z;
002500 while( sqlite3Isspace(*z) ) z++;
002501 }
002502 }
002503 if( z ) printf("SQL: [%s]\n", z);
002504 }
002505 #endif
002506
002507 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
002508 /*
002509 ** Print an IOTRACE message showing SQL content.
002510 */
002511 void sqlite3VdbeIOTraceSql(Vdbe *p){
002512 int nOp = p->nOp;
002513 VdbeOp *pOp;
002514 if( sqlite3IoTrace==0 ) return;
002515 if( nOp<1 ) return;
002516 pOp = &p->aOp[0];
002517 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
002518 int i, j;
002519 char z[1000];
002520 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
002521 for(i=0; sqlite3Isspace(z[i]); i++){}
002522 for(j=0; z[i]; i++){
002523 if( sqlite3Isspace(z[i]) ){
002524 if( z[i-1]!=' ' ){
002525 z[j++] = ' ';
002526 }
002527 }else{
002528 z[j++] = z[i];
002529 }
002530 }
002531 z[j] = 0;
002532 sqlite3IoTrace("SQL %s\n", z);
002533 }
002534 }
002535 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
002536
002537 /* An instance of this object describes bulk memory available for use
002538 ** by subcomponents of a prepared statement. Space is allocated out
002539 ** of a ReusableSpace object by the allocSpace() routine below.
002540 */
002541 struct ReusableSpace {
002542 u8 *pSpace; /* Available memory */
002543 sqlite3_int64 nFree; /* Bytes of available memory */
002544 sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
002545 };
002546
002547 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
002548 ** from the ReusableSpace object. Return a pointer to the allocated
002549 ** memory on success. If insufficient memory is available in the
002550 ** ReusableSpace object, increase the ReusableSpace.nNeeded
002551 ** value by the amount needed and return NULL.
002552 **
002553 ** If pBuf is not initially NULL, that means that the memory has already
002554 ** been allocated by a prior call to this routine, so just return a copy
002555 ** of pBuf and leave ReusableSpace unchanged.
002556 **
002557 ** This allocator is employed to repurpose unused slots at the end of the
002558 ** opcode array of prepared state for other memory needs of the prepared
002559 ** statement.
002560 */
002561 static void *allocSpace(
002562 struct ReusableSpace *p, /* Bulk memory available for allocation */
002563 void *pBuf, /* Pointer to a prior allocation */
002564 sqlite3_int64 nByte /* Bytes of memory needed. */
002565 ){
002566 assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
002567 if( pBuf==0 ){
002568 nByte = ROUND8P(nByte);
002569 if( nByte <= p->nFree ){
002570 p->nFree -= nByte;
002571 pBuf = &p->pSpace[p->nFree];
002572 }else{
002573 p->nNeeded += nByte;
002574 }
002575 }
002576 assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
002577 return pBuf;
002578 }
002579
002580 /*
002581 ** Rewind the VDBE back to the beginning in preparation for
002582 ** running it.
002583 */
002584 void sqlite3VdbeRewind(Vdbe *p){
002585 #if defined(SQLITE_DEBUG)
002586 int i;
002587 #endif
002588 assert( p!=0 );
002589 assert( p->eVdbeState==VDBE_INIT_STATE
002590 || p->eVdbeState==VDBE_READY_STATE
002591 || p->eVdbeState==VDBE_HALT_STATE );
002592
002593 /* There should be at least one opcode.
002594 */
002595 assert( p->nOp>0 );
002596
002597 p->eVdbeState = VDBE_READY_STATE;
002598
002599 #ifdef SQLITE_DEBUG
002600 for(i=0; i<p->nMem; i++){
002601 assert( p->aMem[i].db==p->db );
002602 }
002603 #endif
002604 p->pc = -1;
002605 p->rc = SQLITE_OK;
002606 p->errorAction = OE_Abort;
002607 p->nChange = 0;
002608 p->cacheCtr = 1;
002609 p->minWriteFileFormat = 255;
002610 p->iStatement = 0;
002611 p->nFkConstraint = 0;
002612 #ifdef VDBE_PROFILE
002613 for(i=0; i<p->nOp; i++){
002614 p->aOp[i].nExec = 0;
002615 p->aOp[i].nCycle = 0;
002616 }
002617 #endif
002618 }
002619
002620 /*
002621 ** Prepare a virtual machine for execution for the first time after
002622 ** creating the virtual machine. This involves things such
002623 ** as allocating registers and initializing the program counter.
002624 ** After the VDBE has be prepped, it can be executed by one or more
002625 ** calls to sqlite3VdbeExec().
002626 **
002627 ** This function may be called exactly once on each virtual machine.
002628 ** After this routine is called the VM has been "packaged" and is ready
002629 ** to run. After this routine is called, further calls to
002630 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
002631 ** the Vdbe from the Parse object that helped generate it so that the
002632 ** the Vdbe becomes an independent entity and the Parse object can be
002633 ** destroyed.
002634 **
002635 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
002636 ** to its initial state after it has been run.
002637 */
002638 void sqlite3VdbeMakeReady(
002639 Vdbe *p, /* The VDBE */
002640 Parse *pParse /* Parsing context */
002641 ){
002642 sqlite3 *db; /* The database connection */
002643 int nVar; /* Number of parameters */
002644 int nMem; /* Number of VM memory registers */
002645 int nCursor; /* Number of cursors required */
002646 int nArg; /* Number of arguments in subprograms */
002647 int n; /* Loop counter */
002648 struct ReusableSpace x; /* Reusable bulk memory */
002649
002650 assert( p!=0 );
002651 assert( p->nOp>0 );
002652 assert( pParse!=0 );
002653 assert( p->eVdbeState==VDBE_INIT_STATE );
002654 assert( pParse==p->pParse );
002655 assert( pParse->db==p->db );
002656 p->pVList = pParse->pVList;
002657 pParse->pVList = 0;
002658 db = p->db;
002659 assert( db->mallocFailed==0 );
002660 nVar = pParse->nVar;
002661 nMem = pParse->nMem;
002662 nCursor = pParse->nTab;
002663 nArg = pParse->nMaxArg;
002664
002665 /* Each cursor uses a memory cell. The first cursor (cursor 0) can
002666 ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
002667 ** space at the end of aMem[] for cursors 1 and greater.
002668 ** See also: allocateCursor().
002669 */
002670 nMem += nCursor;
002671 if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
002672
002673 /* Figure out how much reusable memory is available at the end of the
002674 ** opcode array. This extra memory will be reallocated for other elements
002675 ** of the prepared statement.
002676 */
002677 n = ROUND8P(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
002678 x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
002679 assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
002680 x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
002681 assert( x.nFree>=0 );
002682 assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
002683
002684 resolveP2Values(p, &nArg);
002685 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
002686 if( pParse->explain ){
002687 if( nMem<10 ) nMem = 10;
002688 p->explain = pParse->explain;
002689 p->nResColumn = 12 - 4*p->explain;
002690 }
002691 p->expired = 0;
002692
002693 /* Memory for registers, parameters, cursor, etc, is allocated in one or two
002694 ** passes. On the first pass, we try to reuse unused memory at the
002695 ** end of the opcode array. If we are unable to satisfy all memory
002696 ** requirements by reusing the opcode array tail, then the second
002697 ** pass will fill in the remainder using a fresh memory allocation.
002698 **
002699 ** This two-pass approach that reuses as much memory as possible from
002700 ** the leftover memory at the end of the opcode array. This can significantly
002701 ** reduce the amount of memory held by a prepared statement.
002702 */
002703 x.nNeeded = 0;
002704 p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
002705 p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
002706 p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
002707 p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
002708 if( x.nNeeded ){
002709 x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
002710 x.nFree = x.nNeeded;
002711 if( !db->mallocFailed ){
002712 p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
002713 p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
002714 p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
002715 p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
002716 }
002717 }
002718
002719 if( db->mallocFailed ){
002720 p->nVar = 0;
002721 p->nCursor = 0;
002722 p->nMem = 0;
002723 }else{
002724 p->nCursor = nCursor;
002725 p->nVar = (ynVar)nVar;
002726 initMemArray(p->aVar, nVar, db, MEM_Null);
002727 p->nMem = nMem;
002728 initMemArray(p->aMem, nMem, db, MEM_Undefined);
002729 memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
002730 }
002731 sqlite3VdbeRewind(p);
002732 }
002733
002734 /*
002735 ** Close a VDBE cursor and release all the resources that cursor
002736 ** happens to hold.
002737 */
002738 void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
002739 if( pCx ) sqlite3VdbeFreeCursorNN(p,pCx);
002740 }
002741 static SQLITE_NOINLINE void freeCursorWithCache(Vdbe *p, VdbeCursor *pCx){
002742 VdbeTxtBlbCache *pCache = pCx->pCache;
002743 assert( pCx->colCache );
002744 pCx->colCache = 0;
002745 pCx->pCache = 0;
002746 if( pCache->pCValue ){
002747 sqlite3RCStrUnref(pCache->pCValue);
002748 pCache->pCValue = 0;
002749 }
002750 sqlite3DbFree(p->db, pCache);
002751 sqlite3VdbeFreeCursorNN(p, pCx);
002752 }
002753 void sqlite3VdbeFreeCursorNN(Vdbe *p, VdbeCursor *pCx){
002754 if( pCx->colCache ){
002755 freeCursorWithCache(p, pCx);
002756 return;
002757 }
002758 switch( pCx->eCurType ){
002759 case CURTYPE_SORTER: {
002760 sqlite3VdbeSorterClose(p->db, pCx);
002761 break;
002762 }
002763 case CURTYPE_BTREE: {
002764 assert( pCx->uc.pCursor!=0 );
002765 sqlite3BtreeCloseCursor(pCx->uc.pCursor);
002766 break;
002767 }
002768 #ifndef SQLITE_OMIT_VIRTUALTABLE
002769 case CURTYPE_VTAB: {
002770 sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
002771 const sqlite3_module *pModule = pVCur->pVtab->pModule;
002772 assert( pVCur->pVtab->nRef>0 );
002773 pVCur->pVtab->nRef--;
002774 pModule->xClose(pVCur);
002775 break;
002776 }
002777 #endif
002778 }
002779 }
002780
002781 /*
002782 ** Close all cursors in the current frame.
002783 */
002784 static void closeCursorsInFrame(Vdbe *p){
002785 int i;
002786 for(i=0; i<p->nCursor; i++){
002787 VdbeCursor *pC = p->apCsr[i];
002788 if( pC ){
002789 sqlite3VdbeFreeCursorNN(p, pC);
002790 p->apCsr[i] = 0;
002791 }
002792 }
002793 }
002794
002795 /*
002796 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
002797 ** is used, for example, when a trigger sub-program is halted to restore
002798 ** control to the main program.
002799 */
002800 int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
002801 Vdbe *v = pFrame->v;
002802 closeCursorsInFrame(v);
002803 v->aOp = pFrame->aOp;
002804 v->nOp = pFrame->nOp;
002805 v->aMem = pFrame->aMem;
002806 v->nMem = pFrame->nMem;
002807 v->apCsr = pFrame->apCsr;
002808 v->nCursor = pFrame->nCursor;
002809 v->db->lastRowid = pFrame->lastRowid;
002810 v->nChange = pFrame->nChange;
002811 v->db->nChange = pFrame->nDbChange;
002812 sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
002813 v->pAuxData = pFrame->pAuxData;
002814 pFrame->pAuxData = 0;
002815 return pFrame->pc;
002816 }
002817
002818 /*
002819 ** Close all cursors.
002820 **
002821 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
002822 ** cell array. This is necessary as the memory cell array may contain
002823 ** pointers to VdbeFrame objects, which may in turn contain pointers to
002824 ** open cursors.
002825 */
002826 static void closeAllCursors(Vdbe *p){
002827 if( p->pFrame ){
002828 VdbeFrame *pFrame;
002829 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
002830 sqlite3VdbeFrameRestore(pFrame);
002831 p->pFrame = 0;
002832 p->nFrame = 0;
002833 }
002834 assert( p->nFrame==0 );
002835 closeCursorsInFrame(p);
002836 releaseMemArray(p->aMem, p->nMem);
002837 while( p->pDelFrame ){
002838 VdbeFrame *pDel = p->pDelFrame;
002839 p->pDelFrame = pDel->pParent;
002840 sqlite3VdbeFrameDelete(pDel);
002841 }
002842
002843 /* Delete any auxdata allocations made by the VM */
002844 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
002845 assert( p->pAuxData==0 );
002846 }
002847
002848 /*
002849 ** Set the number of result columns that will be returned by this SQL
002850 ** statement. This is now set at compile time, rather than during
002851 ** execution of the vdbe program so that sqlite3_column_count() can
002852 ** be called on an SQL statement before sqlite3_step().
002853 */
002854 void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
002855 int n;
002856 sqlite3 *db = p->db;
002857
002858 if( p->nResAlloc ){
002859 releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
002860 sqlite3DbFree(db, p->aColName);
002861 }
002862 n = nResColumn*COLNAME_N;
002863 p->nResColumn = p->nResAlloc = (u16)nResColumn;
002864 p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
002865 if( p->aColName==0 ) return;
002866 initMemArray(p->aColName, n, db, MEM_Null);
002867 }
002868
002869 /*
002870 ** Set the name of the idx'th column to be returned by the SQL statement.
002871 ** zName must be a pointer to a nul terminated string.
002872 **
002873 ** This call must be made after a call to sqlite3VdbeSetNumCols().
002874 **
002875 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
002876 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
002877 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
002878 */
002879 int sqlite3VdbeSetColName(
002880 Vdbe *p, /* Vdbe being configured */
002881 int idx, /* Index of column zName applies to */
002882 int var, /* One of the COLNAME_* constants */
002883 const char *zName, /* Pointer to buffer containing name */
002884 void (*xDel)(void*) /* Memory management strategy for zName */
002885 ){
002886 int rc;
002887 Mem *pColName;
002888 assert( idx<p->nResAlloc );
002889 assert( var<COLNAME_N );
002890 if( p->db->mallocFailed ){
002891 assert( !zName || xDel!=SQLITE_DYNAMIC );
002892 return SQLITE_NOMEM_BKPT;
002893 }
002894 assert( p->aColName!=0 );
002895 pColName = &(p->aColName[idx+var*p->nResAlloc]);
002896 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
002897 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
002898 return rc;
002899 }
002900
002901 /*
002902 ** A read or write transaction may or may not be active on database handle
002903 ** db. If a transaction is active, commit it. If there is a
002904 ** write-transaction spanning more than one database file, this routine
002905 ** takes care of the super-journal trickery.
002906 */
002907 static int vdbeCommit(sqlite3 *db, Vdbe *p){
002908 int i;
002909 int nTrans = 0; /* Number of databases with an active write-transaction
002910 ** that are candidates for a two-phase commit using a
002911 ** super-journal */
002912 int rc = SQLITE_OK;
002913 int needXcommit = 0;
002914
002915 #ifdef SQLITE_OMIT_VIRTUALTABLE
002916 /* With this option, sqlite3VtabSync() is defined to be simply
002917 ** SQLITE_OK so p is not used.
002918 */
002919 UNUSED_PARAMETER(p);
002920 #endif
002921
002922 /* Before doing anything else, call the xSync() callback for any
002923 ** virtual module tables written in this transaction. This has to
002924 ** be done before determining whether a super-journal file is
002925 ** required, as an xSync() callback may add an attached database
002926 ** to the transaction.
002927 */
002928 rc = sqlite3VtabSync(db, p);
002929
002930 /* This loop determines (a) if the commit hook should be invoked and
002931 ** (b) how many database files have open write transactions, not
002932 ** including the temp database. (b) is important because if more than
002933 ** one database file has an open write transaction, a super-journal
002934 ** file is required for an atomic commit.
002935 */
002936 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
002937 Btree *pBt = db->aDb[i].pBt;
002938 if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
002939 /* Whether or not a database might need a super-journal depends upon
002940 ** its journal mode (among other things). This matrix determines which
002941 ** journal modes use a super-journal and which do not */
002942 static const u8 aMJNeeded[] = {
002943 /* DELETE */ 1,
002944 /* PERSIST */ 1,
002945 /* OFF */ 0,
002946 /* TRUNCATE */ 1,
002947 /* MEMORY */ 0,
002948 /* WAL */ 0
002949 };
002950 Pager *pPager; /* Pager associated with pBt */
002951 needXcommit = 1;
002952 sqlite3BtreeEnter(pBt);
002953 pPager = sqlite3BtreePager(pBt);
002954 if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
002955 && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
002956 && sqlite3PagerIsMemdb(pPager)==0
002957 ){
002958 assert( i!=1 );
002959 nTrans++;
002960 }
002961 rc = sqlite3PagerExclusiveLock(pPager);
002962 sqlite3BtreeLeave(pBt);
002963 }
002964 }
002965 if( rc!=SQLITE_OK ){
002966 return rc;
002967 }
002968
002969 /* If there are any write-transactions at all, invoke the commit hook */
002970 if( needXcommit && db->xCommitCallback ){
002971 rc = db->xCommitCallback(db->pCommitArg);
002972 if( rc ){
002973 return SQLITE_CONSTRAINT_COMMITHOOK;
002974 }
002975 }
002976
002977 /* The simple case - no more than one database file (not counting the
002978 ** TEMP database) has a transaction active. There is no need for the
002979 ** super-journal.
002980 **
002981 ** If the return value of sqlite3BtreeGetFilename() is a zero length
002982 ** string, it means the main database is :memory: or a temp file. In
002983 ** that case we do not support atomic multi-file commits, so use the
002984 ** simple case then too.
002985 */
002986 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
002987 || nTrans<=1
002988 ){
002989 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
002990 Btree *pBt = db->aDb[i].pBt;
002991 if( pBt ){
002992 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
002993 }
002994 }
002995
002996 /* Do the commit only if all databases successfully complete phase 1.
002997 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
002998 ** IO error while deleting or truncating a journal file. It is unlikely,
002999 ** but could happen. In this case abandon processing and return the error.
003000 */
003001 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
003002 Btree *pBt = db->aDb[i].pBt;
003003 if( pBt ){
003004 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
003005 }
003006 }
003007 if( rc==SQLITE_OK ){
003008 sqlite3VtabCommit(db);
003009 }
003010 }
003011
003012 /* The complex case - There is a multi-file write-transaction active.
003013 ** This requires a super-journal file to ensure the transaction is
003014 ** committed atomically.
003015 */
003016 #ifndef SQLITE_OMIT_DISKIO
003017 else{
003018 sqlite3_vfs *pVfs = db->pVfs;
003019 char *zSuper = 0; /* File-name for the super-journal */
003020 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
003021 sqlite3_file *pSuperJrnl = 0;
003022 i64 offset = 0;
003023 int res;
003024 int retryCount = 0;
003025 int nMainFile;
003026
003027 /* Select a super-journal file name */
003028 nMainFile = sqlite3Strlen30(zMainFile);
003029 zSuper = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0);
003030 if( zSuper==0 ) return SQLITE_NOMEM_BKPT;
003031 zSuper += 4;
003032 do {
003033 u32 iRandom;
003034 if( retryCount ){
003035 if( retryCount>100 ){
003036 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zSuper);
003037 sqlite3OsDelete(pVfs, zSuper, 0);
003038 break;
003039 }else if( retryCount==1 ){
003040 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zSuper);
003041 }
003042 }
003043 retryCount++;
003044 sqlite3_randomness(sizeof(iRandom), &iRandom);
003045 sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
003046 (iRandom>>8)&0xffffff, iRandom&0xff);
003047 /* The antipenultimate character of the super-journal name must
003048 ** be "9" to avoid name collisions when using 8+3 filenames. */
003049 assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
003050 sqlite3FileSuffix3(zMainFile, zSuper);
003051 rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
003052 }while( rc==SQLITE_OK && res );
003053 if( rc==SQLITE_OK ){
003054 /* Open the super-journal. */
003055 rc = sqlite3OsOpenMalloc(pVfs, zSuper, &pSuperJrnl,
003056 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
003057 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_SUPER_JOURNAL, 0
003058 );
003059 }
003060 if( rc!=SQLITE_OK ){
003061 sqlite3DbFree(db, zSuper-4);
003062 return rc;
003063 }
003064
003065 /* Write the name of each database file in the transaction into the new
003066 ** super-journal file. If an error occurs at this point close
003067 ** and delete the super-journal file. All the individual journal files
003068 ** still have 'null' as the super-journal pointer, so they will roll
003069 ** back independently if a failure occurs.
003070 */
003071 for(i=0; i<db->nDb; i++){
003072 Btree *pBt = db->aDb[i].pBt;
003073 if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
003074 char const *zFile = sqlite3BtreeGetJournalname(pBt);
003075 if( zFile==0 ){
003076 continue; /* Ignore TEMP and :memory: databases */
003077 }
003078 assert( zFile[0]!=0 );
003079 rc = sqlite3OsWrite(pSuperJrnl, zFile, sqlite3Strlen30(zFile)+1,offset);
003080 offset += sqlite3Strlen30(zFile)+1;
003081 if( rc!=SQLITE_OK ){
003082 sqlite3OsCloseFree(pSuperJrnl);
003083 sqlite3OsDelete(pVfs, zSuper, 0);
003084 sqlite3DbFree(db, zSuper-4);
003085 return rc;
003086 }
003087 }
003088 }
003089
003090 /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
003091 ** flag is set this is not required.
003092 */
003093 if( 0==(sqlite3OsDeviceCharacteristics(pSuperJrnl)&SQLITE_IOCAP_SEQUENTIAL)
003094 && SQLITE_OK!=(rc = sqlite3OsSync(pSuperJrnl, SQLITE_SYNC_NORMAL))
003095 ){
003096 sqlite3OsCloseFree(pSuperJrnl);
003097 sqlite3OsDelete(pVfs, zSuper, 0);
003098 sqlite3DbFree(db, zSuper-4);
003099 return rc;
003100 }
003101
003102 /* Sync all the db files involved in the transaction. The same call
003103 ** sets the super-journal pointer in each individual journal. If
003104 ** an error occurs here, do not delete the super-journal file.
003105 **
003106 ** If the error occurs during the first call to
003107 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
003108 ** super-journal file will be orphaned. But we cannot delete it,
003109 ** in case the super-journal file name was written into the journal
003110 ** file before the failure occurred.
003111 */
003112 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
003113 Btree *pBt = db->aDb[i].pBt;
003114 if( pBt ){
003115 rc = sqlite3BtreeCommitPhaseOne(pBt, zSuper);
003116 }
003117 }
003118 sqlite3OsCloseFree(pSuperJrnl);
003119 assert( rc!=SQLITE_BUSY );
003120 if( rc!=SQLITE_OK ){
003121 sqlite3DbFree(db, zSuper-4);
003122 return rc;
003123 }
003124
003125 /* Delete the super-journal file. This commits the transaction. After
003126 ** doing this the directory is synced again before any individual
003127 ** transaction files are deleted.
003128 */
003129 rc = sqlite3OsDelete(pVfs, zSuper, 1);
003130 sqlite3DbFree(db, zSuper-4);
003131 zSuper = 0;
003132 if( rc ){
003133 return rc;
003134 }
003135
003136 /* All files and directories have already been synced, so the following
003137 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
003138 ** deleting or truncating journals. If something goes wrong while
003139 ** this is happening we don't really care. The integrity of the
003140 ** transaction is already guaranteed, but some stray 'cold' journals
003141 ** may be lying around. Returning an error code won't help matters.
003142 */
003143 disable_simulated_io_errors();
003144 sqlite3BeginBenignMalloc();
003145 for(i=0; i<db->nDb; i++){
003146 Btree *pBt = db->aDb[i].pBt;
003147 if( pBt ){
003148 sqlite3BtreeCommitPhaseTwo(pBt, 1);
003149 }
003150 }
003151 sqlite3EndBenignMalloc();
003152 enable_simulated_io_errors();
003153
003154 sqlite3VtabCommit(db);
003155 }
003156 #endif
003157
003158 return rc;
003159 }
003160
003161 /*
003162 ** This routine checks that the sqlite3.nVdbeActive count variable
003163 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
003164 ** currently active. An assertion fails if the two counts do not match.
003165 ** This is an internal self-check only - it is not an essential processing
003166 ** step.
003167 **
003168 ** This is a no-op if NDEBUG is defined.
003169 */
003170 #ifndef NDEBUG
003171 static void checkActiveVdbeCnt(sqlite3 *db){
003172 Vdbe *p;
003173 int cnt = 0;
003174 int nWrite = 0;
003175 int nRead = 0;
003176 p = db->pVdbe;
003177 while( p ){
003178 if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
003179 cnt++;
003180 if( p->readOnly==0 ) nWrite++;
003181 if( p->bIsReader ) nRead++;
003182 }
003183 p = p->pVNext;
003184 }
003185 assert( cnt==db->nVdbeActive );
003186 assert( nWrite==db->nVdbeWrite );
003187 assert( nRead==db->nVdbeRead );
003188 }
003189 #else
003190 #define checkActiveVdbeCnt(x)
003191 #endif
003192
003193 /*
003194 ** If the Vdbe passed as the first argument opened a statement-transaction,
003195 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
003196 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
003197 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
003198 ** statement transaction is committed.
003199 **
003200 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
003201 ** Otherwise SQLITE_OK.
003202 */
003203 static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
003204 sqlite3 *const db = p->db;
003205 int rc = SQLITE_OK;
003206 int i;
003207 const int iSavepoint = p->iStatement-1;
003208
003209 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
003210 assert( db->nStatement>0 );
003211 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
003212
003213 for(i=0; i<db->nDb; i++){
003214 int rc2 = SQLITE_OK;
003215 Btree *pBt = db->aDb[i].pBt;
003216 if( pBt ){
003217 if( eOp==SAVEPOINT_ROLLBACK ){
003218 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
003219 }
003220 if( rc2==SQLITE_OK ){
003221 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
003222 }
003223 if( rc==SQLITE_OK ){
003224 rc = rc2;
003225 }
003226 }
003227 }
003228 db->nStatement--;
003229 p->iStatement = 0;
003230
003231 if( rc==SQLITE_OK ){
003232 if( eOp==SAVEPOINT_ROLLBACK ){
003233 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
003234 }
003235 if( rc==SQLITE_OK ){
003236 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
003237 }
003238 }
003239
003240 /* If the statement transaction is being rolled back, also restore the
003241 ** database handles deferred constraint counter to the value it had when
003242 ** the statement transaction was opened. */
003243 if( eOp==SAVEPOINT_ROLLBACK ){
003244 db->nDeferredCons = p->nStmtDefCons;
003245 db->nDeferredImmCons = p->nStmtDefImmCons;
003246 }
003247 return rc;
003248 }
003249 int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
003250 if( p->db->nStatement && p->iStatement ){
003251 return vdbeCloseStatement(p, eOp);
003252 }
003253 return SQLITE_OK;
003254 }
003255
003256
003257 /*
003258 ** This function is called when a transaction opened by the database
003259 ** handle associated with the VM passed as an argument is about to be
003260 ** committed. If there are outstanding deferred foreign key constraint
003261 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
003262 **
003263 ** If there are outstanding FK violations and this function returns
003264 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
003265 ** and write an error message to it. Then return SQLITE_ERROR.
003266 */
003267 #ifndef SQLITE_OMIT_FOREIGN_KEY
003268 int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
003269 sqlite3 *db = p->db;
003270 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
003271 || (!deferred && p->nFkConstraint>0)
003272 ){
003273 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
003274 p->errorAction = OE_Abort;
003275 sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
003276 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;
003277 return SQLITE_CONSTRAINT_FOREIGNKEY;
003278 }
003279 return SQLITE_OK;
003280 }
003281 #endif
003282
003283 /*
003284 ** This routine is called the when a VDBE tries to halt. If the VDBE
003285 ** has made changes and is in autocommit mode, then commit those
003286 ** changes. If a rollback is needed, then do the rollback.
003287 **
003288 ** This routine is the only way to move the sqlite3eOpenState of a VM from
003289 ** SQLITE_STATE_RUN to SQLITE_STATE_HALT. It is harmless to
003290 ** call this on a VM that is in the SQLITE_STATE_HALT state.
003291 **
003292 ** Return an error code. If the commit could not complete because of
003293 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
003294 ** means the close did not happen and needs to be repeated.
003295 */
003296 int sqlite3VdbeHalt(Vdbe *p){
003297 int rc; /* Used to store transient return codes */
003298 sqlite3 *db = p->db;
003299
003300 /* This function contains the logic that determines if a statement or
003301 ** transaction will be committed or rolled back as a result of the
003302 ** execution of this virtual machine.
003303 **
003304 ** If any of the following errors occur:
003305 **
003306 ** SQLITE_NOMEM
003307 ** SQLITE_IOERR
003308 ** SQLITE_FULL
003309 ** SQLITE_INTERRUPT
003310 **
003311 ** Then the internal cache might have been left in an inconsistent
003312 ** state. We need to rollback the statement transaction, if there is
003313 ** one, or the complete transaction if there is no statement transaction.
003314 */
003315
003316 assert( p->eVdbeState==VDBE_RUN_STATE );
003317 if( db->mallocFailed ){
003318 p->rc = SQLITE_NOMEM_BKPT;
003319 }
003320 closeAllCursors(p);
003321 checkActiveVdbeCnt(db);
003322
003323 /* No commit or rollback needed if the program never started or if the
003324 ** SQL statement does not read or write a database file. */
003325 if( p->bIsReader ){
003326 int mrc; /* Primary error code from p->rc */
003327 int eStatementOp = 0;
003328 int isSpecialError; /* Set to true if a 'special' error */
003329
003330 /* Lock all btrees used by the statement */
003331 sqlite3VdbeEnter(p);
003332
003333 /* Check for one of the special errors */
003334 if( p->rc ){
003335 mrc = p->rc & 0xff;
003336 isSpecialError = mrc==SQLITE_NOMEM
003337 || mrc==SQLITE_IOERR
003338 || mrc==SQLITE_INTERRUPT
003339 || mrc==SQLITE_FULL;
003340 }else{
003341 mrc = isSpecialError = 0;
003342 }
003343 if( isSpecialError ){
003344 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
003345 ** no rollback is necessary. Otherwise, at least a savepoint
003346 ** transaction must be rolled back to restore the database to a
003347 ** consistent state.
003348 **
003349 ** Even if the statement is read-only, it is important to perform
003350 ** a statement or transaction rollback operation. If the error
003351 ** occurred while writing to the journal, sub-journal or database
003352 ** file as part of an effort to free up cache space (see function
003353 ** pagerStress() in pager.c), the rollback is required to restore
003354 ** the pager to a consistent state.
003355 */
003356 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
003357 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
003358 eStatementOp = SAVEPOINT_ROLLBACK;
003359 }else{
003360 /* We are forced to roll back the active transaction. Before doing
003361 ** so, abort any other statements this handle currently has active.
003362 */
003363 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003364 sqlite3CloseSavepoints(db);
003365 db->autoCommit = 1;
003366 p->nChange = 0;
003367 }
003368 }
003369 }
003370
003371 /* Check for immediate foreign key violations. */
003372 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
003373 (void)sqlite3VdbeCheckFk(p, 0);
003374 }
003375
003376 /* If the auto-commit flag is set and this is the only active writer
003377 ** VM, then we do either a commit or rollback of the current transaction.
003378 **
003379 ** Note: This block also runs if one of the special errors handled
003380 ** above has occurred.
003381 */
003382 if( !sqlite3VtabInSync(db)
003383 && db->autoCommit
003384 && db->nVdbeWrite==(p->readOnly==0)
003385 ){
003386 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
003387 rc = sqlite3VdbeCheckFk(p, 1);
003388 if( rc!=SQLITE_OK ){
003389 if( NEVER(p->readOnly) ){
003390 sqlite3VdbeLeave(p);
003391 return SQLITE_ERROR;
003392 }
003393 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
003394 }else if( db->flags & SQLITE_CorruptRdOnly ){
003395 rc = SQLITE_CORRUPT;
003396 db->flags &= ~SQLITE_CorruptRdOnly;
003397 }else{
003398 /* The auto-commit flag is true, the vdbe program was successful
003399 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
003400 ** key constraints to hold up the transaction. This means a commit
003401 ** is required. */
003402 rc = vdbeCommit(db, p);
003403 }
003404 if( rc==SQLITE_BUSY && p->readOnly ){
003405 sqlite3VdbeLeave(p);
003406 return SQLITE_BUSY;
003407 }else if( rc!=SQLITE_OK ){
003408 sqlite3SystemError(db, rc);
003409 p->rc = rc;
003410 sqlite3RollbackAll(db, SQLITE_OK);
003411 p->nChange = 0;
003412 }else{
003413 db->nDeferredCons = 0;
003414 db->nDeferredImmCons = 0;
003415 db->flags &= ~(u64)SQLITE_DeferFKs;
003416 sqlite3CommitInternalChanges(db);
003417 }
003418 }else if( p->rc==SQLITE_SCHEMA && db->nVdbeActive>1 ){
003419 p->nChange = 0;
003420 }else{
003421 sqlite3RollbackAll(db, SQLITE_OK);
003422 p->nChange = 0;
003423 }
003424 db->nStatement = 0;
003425 }else if( eStatementOp==0 ){
003426 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
003427 eStatementOp = SAVEPOINT_RELEASE;
003428 }else if( p->errorAction==OE_Abort ){
003429 eStatementOp = SAVEPOINT_ROLLBACK;
003430 }else{
003431 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003432 sqlite3CloseSavepoints(db);
003433 db->autoCommit = 1;
003434 p->nChange = 0;
003435 }
003436 }
003437
003438 /* If eStatementOp is non-zero, then a statement transaction needs to
003439 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
003440 ** do so. If this operation returns an error, and the current statement
003441 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
003442 ** current statement error code.
003443 */
003444 if( eStatementOp ){
003445 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
003446 if( rc ){
003447 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
003448 p->rc = rc;
003449 sqlite3DbFree(db, p->zErrMsg);
003450 p->zErrMsg = 0;
003451 }
003452 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
003453 sqlite3CloseSavepoints(db);
003454 db->autoCommit = 1;
003455 p->nChange = 0;
003456 }
003457 }
003458
003459 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
003460 ** has been rolled back, update the database connection change-counter.
003461 */
003462 if( p->changeCntOn ){
003463 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
003464 sqlite3VdbeSetChanges(db, p->nChange);
003465 }else{
003466 sqlite3VdbeSetChanges(db, 0);
003467 }
003468 p->nChange = 0;
003469 }
003470
003471 /* Release the locks */
003472 sqlite3VdbeLeave(p);
003473 }
003474
003475 /* We have successfully halted and closed the VM. Record this fact. */
003476 db->nVdbeActive--;
003477 if( !p->readOnly ) db->nVdbeWrite--;
003478 if( p->bIsReader ) db->nVdbeRead--;
003479 assert( db->nVdbeActive>=db->nVdbeRead );
003480 assert( db->nVdbeRead>=db->nVdbeWrite );
003481 assert( db->nVdbeWrite>=0 );
003482 p->eVdbeState = VDBE_HALT_STATE;
003483 checkActiveVdbeCnt(db);
003484 if( db->mallocFailed ){
003485 p->rc = SQLITE_NOMEM_BKPT;
003486 }
003487
003488 /* If the auto-commit flag is set to true, then any locks that were held
003489 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
003490 ** to invoke any required unlock-notify callbacks.
003491 */
003492 if( db->autoCommit ){
003493 sqlite3ConnectionUnlocked(db);
003494 }
003495
003496 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
003497 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
003498 }
003499
003500
003501 /*
003502 ** Each VDBE holds the result of the most recent sqlite3_step() call
003503 ** in p->rc. This routine sets that result back to SQLITE_OK.
003504 */
003505 void sqlite3VdbeResetStepResult(Vdbe *p){
003506 p->rc = SQLITE_OK;
003507 }
003508
003509 /*
003510 ** Copy the error code and error message belonging to the VDBE passed
003511 ** as the first argument to its database handle (so that they will be
003512 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
003513 **
003514 ** This function does not clear the VDBE error code or message, just
003515 ** copies them to the database handle.
003516 */
003517 int sqlite3VdbeTransferError(Vdbe *p){
003518 sqlite3 *db = p->db;
003519 int rc = p->rc;
003520 if( p->zErrMsg ){
003521 db->bBenignMalloc++;
003522 sqlite3BeginBenignMalloc();
003523 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
003524 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
003525 sqlite3EndBenignMalloc();
003526 db->bBenignMalloc--;
003527 }else if( db->pErr ){
003528 sqlite3ValueSetNull(db->pErr);
003529 }
003530 db->errCode = rc;
003531 db->errByteOffset = -1;
003532 return rc;
003533 }
003534
003535 #ifdef SQLITE_ENABLE_SQLLOG
003536 /*
003537 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
003538 ** invoke it.
003539 */
003540 static void vdbeInvokeSqllog(Vdbe *v){
003541 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
003542 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
003543 assert( v->db->init.busy==0 );
003544 if( zExpanded ){
003545 sqlite3GlobalConfig.xSqllog(
003546 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
003547 );
003548 sqlite3DbFree(v->db, zExpanded);
003549 }
003550 }
003551 }
003552 #else
003553 # define vdbeInvokeSqllog(x)
003554 #endif
003555
003556 /*
003557 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
003558 ** Write any error messages into *pzErrMsg. Return the result code.
003559 **
003560 ** After this routine is run, the VDBE should be ready to be executed
003561 ** again.
003562 **
003563 ** To look at it another way, this routine resets the state of the
003564 ** virtual machine from VDBE_RUN_STATE or VDBE_HALT_STATE back to
003565 ** VDBE_READY_STATE.
003566 */
003567 int sqlite3VdbeReset(Vdbe *p){
003568 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
003569 int i;
003570 #endif
003571
003572 sqlite3 *db;
003573 db = p->db;
003574
003575 /* If the VM did not run to completion or if it encountered an
003576 ** error, then it might not have been halted properly. So halt
003577 ** it now.
003578 */
003579 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
003580
003581 /* If the VDBE has been run even partially, then transfer the error code
003582 ** and error message from the VDBE into the main database structure. But
003583 ** if the VDBE has just been set to run but has not actually executed any
003584 ** instructions yet, leave the main database error information unchanged.
003585 */
003586 if( p->pc>=0 ){
003587 vdbeInvokeSqllog(p);
003588 if( db->pErr || p->zErrMsg ){
003589 sqlite3VdbeTransferError(p);
003590 }else{
003591 db->errCode = p->rc;
003592 }
003593 }
003594
003595 /* Reset register contents and reclaim error message memory.
003596 */
003597 #ifdef SQLITE_DEBUG
003598 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
003599 ** Vdbe.aMem[] arrays have already been cleaned up. */
003600 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
003601 if( p->aMem ){
003602 for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
003603 }
003604 #endif
003605 if( p->zErrMsg ){
003606 sqlite3DbFree(db, p->zErrMsg);
003607 p->zErrMsg = 0;
003608 }
003609 p->pResultRow = 0;
003610 #ifdef SQLITE_DEBUG
003611 p->nWrite = 0;
003612 #endif
003613
003614 /* Save profiling information from this VDBE run.
003615 */
003616 #ifdef VDBE_PROFILE
003617 {
003618 FILE *out = fopen("vdbe_profile.out", "a");
003619 if( out ){
003620 fprintf(out, "---- ");
003621 for(i=0; i<p->nOp; i++){
003622 fprintf(out, "%02x", p->aOp[i].opcode);
003623 }
003624 fprintf(out, "\n");
003625 if( p->zSql ){
003626 char c, pc = 0;
003627 fprintf(out, "-- ");
003628 for(i=0; (c = p->zSql[i])!=0; i++){
003629 if( pc=='\n' ) fprintf(out, "-- ");
003630 putc(c, out);
003631 pc = c;
003632 }
003633 if( pc!='\n' ) fprintf(out, "\n");
003634 }
003635 for(i=0; i<p->nOp; i++){
003636 char zHdr[100];
003637 i64 cnt = p->aOp[i].nExec;
003638 i64 cycles = p->aOp[i].nCycle;
003639 sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
003640 cnt,
003641 cycles,
003642 cnt>0 ? cycles/cnt : 0
003643 );
003644 fprintf(out, "%s", zHdr);
003645 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
003646 }
003647 fclose(out);
003648 }
003649 }
003650 #endif
003651 return p->rc & db->errMask;
003652 }
003653
003654 /*
003655 ** Clean up and delete a VDBE after execution. Return an integer which is
003656 ** the result code. Write any error message text into *pzErrMsg.
003657 */
003658 int sqlite3VdbeFinalize(Vdbe *p){
003659 int rc = SQLITE_OK;
003660 assert( VDBE_RUN_STATE>VDBE_READY_STATE );
003661 assert( VDBE_HALT_STATE>VDBE_READY_STATE );
003662 assert( VDBE_INIT_STATE<VDBE_READY_STATE );
003663 if( p->eVdbeState>=VDBE_READY_STATE ){
003664 rc = sqlite3VdbeReset(p);
003665 assert( (rc & p->db->errMask)==rc );
003666 }
003667 sqlite3VdbeDelete(p);
003668 return rc;
003669 }
003670
003671 /*
003672 ** If parameter iOp is less than zero, then invoke the destructor for
003673 ** all auxiliary data pointers currently cached by the VM passed as
003674 ** the first argument.
003675 **
003676 ** Or, if iOp is greater than or equal to zero, then the destructor is
003677 ** only invoked for those auxiliary data pointers created by the user
003678 ** function invoked by the OP_Function opcode at instruction iOp of
003679 ** VM pVdbe, and only then if:
003680 **
003681 ** * the associated function parameter is the 32nd or later (counting
003682 ** from left to right), or
003683 **
003684 ** * the corresponding bit in argument mask is clear (where the first
003685 ** function parameter corresponds to bit 0 etc.).
003686 */
003687 void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
003688 while( *pp ){
003689 AuxData *pAux = *pp;
003690 if( (iOp<0)
003691 || (pAux->iAuxOp==iOp
003692 && pAux->iAuxArg>=0
003693 && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
003694 ){
003695 testcase( pAux->iAuxArg==31 );
003696 if( pAux->xDeleteAux ){
003697 pAux->xDeleteAux(pAux->pAux);
003698 }
003699 *pp = pAux->pNextAux;
003700 sqlite3DbFree(db, pAux);
003701 }else{
003702 pp= &pAux->pNextAux;
003703 }
003704 }
003705 }
003706
003707 /*
003708 ** Free all memory associated with the Vdbe passed as the second argument,
003709 ** except for object itself, which is preserved.
003710 **
003711 ** The difference between this function and sqlite3VdbeDelete() is that
003712 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
003713 ** the database connection and frees the object itself.
003714 */
003715 static void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
003716 SubProgram *pSub, *pNext;
003717 assert( db!=0 );
003718 assert( p->db==0 || p->db==db );
003719 if( p->aColName ){
003720 releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
003721 sqlite3DbNNFreeNN(db, p->aColName);
003722 }
003723 for(pSub=p->pProgram; pSub; pSub=pNext){
003724 pNext = pSub->pNext;
003725 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
003726 sqlite3DbFree(db, pSub);
003727 }
003728 if( p->eVdbeState!=VDBE_INIT_STATE ){
003729 releaseMemArray(p->aVar, p->nVar);
003730 if( p->pVList ) sqlite3DbNNFreeNN(db, p->pVList);
003731 if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
003732 }
003733 vdbeFreeOpArray(db, p->aOp, p->nOp);
003734 if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
003735 #ifdef SQLITE_ENABLE_NORMALIZE
003736 sqlite3DbFree(db, p->zNormSql);
003737 {
003738 DblquoteStr *pThis, *pNxt;
003739 for(pThis=p->pDblStr; pThis; pThis=pNxt){
003740 pNxt = pThis->pNextStr;
003741 sqlite3DbFree(db, pThis);
003742 }
003743 }
003744 #endif
003745 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
003746 {
003747 int i;
003748 for(i=0; i<p->nScan; i++){
003749 sqlite3DbFree(db, p->aScan[i].zName);
003750 }
003751 sqlite3DbFree(db, p->aScan);
003752 }
003753 #endif
003754 }
003755
003756 /*
003757 ** Delete an entire VDBE.
003758 */
003759 void sqlite3VdbeDelete(Vdbe *p){
003760 sqlite3 *db;
003761
003762 assert( p!=0 );
003763 db = p->db;
003764 assert( db!=0 );
003765 assert( sqlite3_mutex_held(db->mutex) );
003766 sqlite3VdbeClearObject(db, p);
003767 if( db->pnBytesFreed==0 ){
003768 assert( p->ppVPrev!=0 );
003769 *p->ppVPrev = p->pVNext;
003770 if( p->pVNext ){
003771 p->pVNext->ppVPrev = p->ppVPrev;
003772 }
003773 }
003774 sqlite3DbNNFreeNN(db, p);
003775 }
003776
003777 /*
003778 ** The cursor "p" has a pending seek operation that has not yet been
003779 ** carried out. Seek the cursor now. If an error occurs, return
003780 ** the appropriate error code.
003781 */
003782 int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
003783 int res, rc;
003784 #ifdef SQLITE_TEST
003785 extern int sqlite3_search_count;
003786 #endif
003787 assert( p->deferredMoveto );
003788 assert( p->isTable );
003789 assert( p->eCurType==CURTYPE_BTREE );
003790 rc = sqlite3BtreeTableMoveto(p->uc.pCursor, p->movetoTarget, 0, &res);
003791 if( rc ) return rc;
003792 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
003793 #ifdef SQLITE_TEST
003794 sqlite3_search_count++;
003795 #endif
003796 p->deferredMoveto = 0;
003797 p->cacheStatus = CACHE_STALE;
003798 return SQLITE_OK;
003799 }
003800
003801 /*
003802 ** Something has moved cursor "p" out of place. Maybe the row it was
003803 ** pointed to was deleted out from under it. Or maybe the btree was
003804 ** rebalanced. Whatever the cause, try to restore "p" to the place it
003805 ** is supposed to be pointing. If the row was deleted out from under the
003806 ** cursor, set the cursor to point to a NULL row.
003807 */
003808 int SQLITE_NOINLINE sqlite3VdbeHandleMovedCursor(VdbeCursor *p){
003809 int isDifferentRow, rc;
003810 assert( p->eCurType==CURTYPE_BTREE );
003811 assert( p->uc.pCursor!=0 );
003812 assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
003813 rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
003814 p->cacheStatus = CACHE_STALE;
003815 if( isDifferentRow ) p->nullRow = 1;
003816 return rc;
003817 }
003818
003819 /*
003820 ** Check to ensure that the cursor is valid. Restore the cursor
003821 ** if need be. Return any I/O error from the restore operation.
003822 */
003823 int sqlite3VdbeCursorRestore(VdbeCursor *p){
003824 assert( p->eCurType==CURTYPE_BTREE || IsNullCursor(p) );
003825 if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
003826 return sqlite3VdbeHandleMovedCursor(p);
003827 }
003828 return SQLITE_OK;
003829 }
003830
003831 /*
003832 ** The following functions:
003833 **
003834 ** sqlite3VdbeSerialType()
003835 ** sqlite3VdbeSerialTypeLen()
003836 ** sqlite3VdbeSerialLen()
003837 ** sqlite3VdbeSerialPut() <--- in-lined into OP_MakeRecord as of 2022-04-02
003838 ** sqlite3VdbeSerialGet()
003839 **
003840 ** encapsulate the code that serializes values for storage in SQLite
003841 ** data and index records. Each serialized value consists of a
003842 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
003843 ** integer, stored as a varint.
003844 **
003845 ** In an SQLite index record, the serial type is stored directly before
003846 ** the blob of data that it corresponds to. In a table record, all serial
003847 ** types are stored at the start of the record, and the blobs of data at
003848 ** the end. Hence these functions allow the caller to handle the
003849 ** serial-type and data blob separately.
003850 **
003851 ** The following table describes the various storage classes for data:
003852 **
003853 ** serial type bytes of data type
003854 ** -------------- --------------- ---------------
003855 ** 0 0 NULL
003856 ** 1 1 signed integer
003857 ** 2 2 signed integer
003858 ** 3 3 signed integer
003859 ** 4 4 signed integer
003860 ** 5 6 signed integer
003861 ** 6 8 signed integer
003862 ** 7 8 IEEE float
003863 ** 8 0 Integer constant 0
003864 ** 9 0 Integer constant 1
003865 ** 10,11 reserved for expansion
003866 ** N>=12 and even (N-12)/2 BLOB
003867 ** N>=13 and odd (N-13)/2 text
003868 **
003869 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
003870 ** of SQLite will not understand those serial types.
003871 */
003872
003873 #if 0 /* Inlined into the OP_MakeRecord opcode */
003874 /*
003875 ** Return the serial-type for the value stored in pMem.
003876 **
003877 ** This routine might convert a large MEM_IntReal value into MEM_Real.
003878 **
003879 ** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord
003880 ** opcode in the byte-code engine. But by moving this routine in-line, we
003881 ** can omit some redundant tests and make that opcode a lot faster. So
003882 ** this routine is now only used by the STAT3 logic and STAT3 support has
003883 ** ended. The code is kept here for historical reference only.
003884 */
003885 u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
003886 int flags = pMem->flags;
003887 u32 n;
003888
003889 assert( pLen!=0 );
003890 if( flags&MEM_Null ){
003891 *pLen = 0;
003892 return 0;
003893 }
003894 if( flags&(MEM_Int|MEM_IntReal) ){
003895 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
003896 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
003897 i64 i = pMem->u.i;
003898 u64 u;
003899 testcase( flags & MEM_Int );
003900 testcase( flags & MEM_IntReal );
003901 if( i<0 ){
003902 u = ~i;
003903 }else{
003904 u = i;
003905 }
003906 if( u<=127 ){
003907 if( (i&1)==i && file_format>=4 ){
003908 *pLen = 0;
003909 return 8+(u32)u;
003910 }else{
003911 *pLen = 1;
003912 return 1;
003913 }
003914 }
003915 if( u<=32767 ){ *pLen = 2; return 2; }
003916 if( u<=8388607 ){ *pLen = 3; return 3; }
003917 if( u<=2147483647 ){ *pLen = 4; return 4; }
003918 if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
003919 *pLen = 8;
003920 if( flags&MEM_IntReal ){
003921 /* If the value is IntReal and is going to take up 8 bytes to store
003922 ** as an integer, then we might as well make it an 8-byte floating
003923 ** point value */
003924 pMem->u.r = (double)pMem->u.i;
003925 pMem->flags &= ~MEM_IntReal;
003926 pMem->flags |= MEM_Real;
003927 return 7;
003928 }
003929 return 6;
003930 }
003931 if( flags&MEM_Real ){
003932 *pLen = 8;
003933 return 7;
003934 }
003935 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
003936 assert( pMem->n>=0 );
003937 n = (u32)pMem->n;
003938 if( flags & MEM_Zero ){
003939 n += pMem->u.nZero;
003940 }
003941 *pLen = n;
003942 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
003943 }
003944 #endif /* inlined into OP_MakeRecord */
003945
003946 /*
003947 ** The sizes for serial types less than 128
003948 */
003949 const u8 sqlite3SmallTypeSizes[128] = {
003950 /* 0 1 2 3 4 5 6 7 8 9 */
003951 /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
003952 /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
003953 /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
003954 /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
003955 /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
003956 /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
003957 /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
003958 /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
003959 /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
003960 /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
003961 /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
003962 /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
003963 /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
003964 };
003965
003966 /*
003967 ** Return the length of the data corresponding to the supplied serial-type.
003968 */
003969 u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
003970 if( serial_type>=128 ){
003971 return (serial_type-12)/2;
003972 }else{
003973 assert( serial_type<12
003974 || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
003975 return sqlite3SmallTypeSizes[serial_type];
003976 }
003977 }
003978 u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
003979 assert( serial_type<128 );
003980 return sqlite3SmallTypeSizes[serial_type];
003981 }
003982
003983 /*
003984 ** If we are on an architecture with mixed-endian floating
003985 ** points (ex: ARM7) then swap the lower 4 bytes with the
003986 ** upper 4 bytes. Return the result.
003987 **
003988 ** For most architectures, this is a no-op.
003989 **
003990 ** (later): It is reported to me that the mixed-endian problem
003991 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
003992 ** that early versions of GCC stored the two words of a 64-bit
003993 ** float in the wrong order. And that error has been propagated
003994 ** ever since. The blame is not necessarily with GCC, though.
003995 ** GCC might have just copying the problem from a prior compiler.
003996 ** I am also told that newer versions of GCC that follow a different
003997 ** ABI get the byte order right.
003998 **
003999 ** Developers using SQLite on an ARM7 should compile and run their
004000 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
004001 ** enabled, some asserts below will ensure that the byte order of
004002 ** floating point values is correct.
004003 **
004004 ** (2007-08-30) Frank van Vugt has studied this problem closely
004005 ** and has send his findings to the SQLite developers. Frank
004006 ** writes that some Linux kernels offer floating point hardware
004007 ** emulation that uses only 32-bit mantissas instead of a full
004008 ** 48-bits as required by the IEEE standard. (This is the
004009 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
004010 ** byte swapping becomes very complicated. To avoid problems,
004011 ** the necessary byte swapping is carried out using a 64-bit integer
004012 ** rather than a 64-bit float. Frank assures us that the code here
004013 ** works for him. We, the developers, have no way to independently
004014 ** verify this, but Frank seems to know what he is talking about
004015 ** so we trust him.
004016 */
004017 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
004018 u64 sqlite3FloatSwap(u64 in){
004019 union {
004020 u64 r;
004021 u32 i[2];
004022 } u;
004023 u32 t;
004024
004025 u.r = in;
004026 t = u.i[0];
004027 u.i[0] = u.i[1];
004028 u.i[1] = t;
004029 return u.r;
004030 }
004031 #endif /* SQLITE_MIXED_ENDIAN_64BIT_FLOAT */
004032
004033
004034 /* Input "x" is a sequence of unsigned characters that represent a
004035 ** big-endian integer. Return the equivalent native integer
004036 */
004037 #define ONE_BYTE_INT(x) ((i8)(x)[0])
004038 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
004039 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
004040 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
004041 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
004042
004043 /*
004044 ** Deserialize the data blob pointed to by buf as serial type serial_type
004045 ** and store the result in pMem.
004046 **
004047 ** This function is implemented as two separate routines for performance.
004048 ** The few cases that require local variables are broken out into a separate
004049 ** routine so that in most cases the overhead of moving the stack pointer
004050 ** is avoided.
004051 */
004052 static void serialGet(
004053 const unsigned char *buf, /* Buffer to deserialize from */
004054 u32 serial_type, /* Serial type to deserialize */
004055 Mem *pMem /* Memory cell to write value into */
004056 ){
004057 u64 x = FOUR_BYTE_UINT(buf);
004058 u32 y = FOUR_BYTE_UINT(buf+4);
004059 x = (x<<32) + y;
004060 if( serial_type==6 ){
004061 /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
004062 ** twos-complement integer. */
004063 pMem->u.i = *(i64*)&x;
004064 pMem->flags = MEM_Int;
004065 testcase( pMem->u.i<0 );
004066 }else{
004067 /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
004068 ** floating point number. */
004069 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
004070 /* Verify that integers and floating point values use the same
004071 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
004072 ** defined that 64-bit floating point values really are mixed
004073 ** endian.
004074 */
004075 static const u64 t1 = ((u64)0x3ff00000)<<32;
004076 static const double r1 = 1.0;
004077 u64 t2 = t1;
004078 swapMixedEndianFloat(t2);
004079 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
004080 #endif
004081 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
004082 swapMixedEndianFloat(x);
004083 memcpy(&pMem->u.r, &x, sizeof(x));
004084 pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
004085 }
004086 }
004087 static int serialGet7(
004088 const unsigned char *buf, /* Buffer to deserialize from */
004089 Mem *pMem /* Memory cell to write value into */
004090 ){
004091 u64 x = FOUR_BYTE_UINT(buf);
004092 u32 y = FOUR_BYTE_UINT(buf+4);
004093 x = (x<<32) + y;
004094 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
004095 swapMixedEndianFloat(x);
004096 memcpy(&pMem->u.r, &x, sizeof(x));
004097 if( IsNaN(x) ){
004098 pMem->flags = MEM_Null;
004099 return 1;
004100 }
004101 pMem->flags = MEM_Real;
004102 return 0;
004103 }
004104 void sqlite3VdbeSerialGet(
004105 const unsigned char *buf, /* Buffer to deserialize from */
004106 u32 serial_type, /* Serial type to deserialize */
004107 Mem *pMem /* Memory cell to write value into */
004108 ){
004109 switch( serial_type ){
004110 case 10: { /* Internal use only: NULL with virtual table
004111 ** UPDATE no-change flag set */
004112 pMem->flags = MEM_Null|MEM_Zero;
004113 pMem->n = 0;
004114 pMem->u.nZero = 0;
004115 return;
004116 }
004117 case 11: /* Reserved for future use */
004118 case 0: { /* Null */
004119 /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
004120 pMem->flags = MEM_Null;
004121 return;
004122 }
004123 case 1: {
004124 /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
004125 ** integer. */
004126 pMem->u.i = ONE_BYTE_INT(buf);
004127 pMem->flags = MEM_Int;
004128 testcase( pMem->u.i<0 );
004129 return;
004130 }
004131 case 2: { /* 2-byte signed integer */
004132 /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
004133 ** twos-complement integer. */
004134 pMem->u.i = TWO_BYTE_INT(buf);
004135 pMem->flags = MEM_Int;
004136 testcase( pMem->u.i<0 );
004137 return;
004138 }
004139 case 3: { /* 3-byte signed integer */
004140 /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
004141 ** twos-complement integer. */
004142 pMem->u.i = THREE_BYTE_INT(buf);
004143 pMem->flags = MEM_Int;
004144 testcase( pMem->u.i<0 );
004145 return;
004146 }
004147 case 4: { /* 4-byte signed integer */
004148 /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
004149 ** twos-complement integer. */
004150 pMem->u.i = FOUR_BYTE_INT(buf);
004151 #ifdef __HP_cc
004152 /* Work around a sign-extension bug in the HP compiler for HP/UX */
004153 if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
004154 #endif
004155 pMem->flags = MEM_Int;
004156 testcase( pMem->u.i<0 );
004157 return;
004158 }
004159 case 5: { /* 6-byte signed integer */
004160 /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
004161 ** twos-complement integer. */
004162 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
004163 pMem->flags = MEM_Int;
004164 testcase( pMem->u.i<0 );
004165 return;
004166 }
004167 case 6: /* 8-byte signed integer */
004168 case 7: { /* IEEE floating point */
004169 /* These use local variables, so do them in a separate routine
004170 ** to avoid having to move the frame pointer in the common case */
004171 serialGet(buf,serial_type,pMem);
004172 return;
004173 }
004174 case 8: /* Integer 0 */
004175 case 9: { /* Integer 1 */
004176 /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
004177 /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
004178 pMem->u.i = serial_type-8;
004179 pMem->flags = MEM_Int;
004180 return;
004181 }
004182 default: {
004183 /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
004184 ** length.
004185 ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
004186 ** (N-13)/2 bytes in length. */
004187 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
004188 pMem->z = (char *)buf;
004189 pMem->n = (serial_type-12)/2;
004190 pMem->flags = aFlag[serial_type&1];
004191 return;
004192 }
004193 }
004194 return;
004195 }
004196 /*
004197 ** This routine is used to allocate sufficient space for an UnpackedRecord
004198 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
004199 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
004200 **
004201 ** The space is either allocated using sqlite3DbMallocRaw() or from within
004202 ** the unaligned buffer passed via the second and third arguments (presumably
004203 ** stack space). If the former, then *ppFree is set to a pointer that should
004204 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
004205 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
004206 ** before returning.
004207 **
004208 ** If an OOM error occurs, NULL is returned.
004209 */
004210 UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
004211 KeyInfo *pKeyInfo /* Description of the record */
004212 ){
004213 UnpackedRecord *p; /* Unpacked record to return */
004214 int nByte; /* Number of bytes required for *p */
004215 nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
004216 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
004217 if( !p ) return 0;
004218 p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))];
004219 assert( pKeyInfo->aSortFlags!=0 );
004220 p->pKeyInfo = pKeyInfo;
004221 p->nField = pKeyInfo->nKeyField + 1;
004222 return p;
004223 }
004224
004225 /*
004226 ** Given the nKey-byte encoding of a record in pKey[], populate the
004227 ** UnpackedRecord structure indicated by the fourth argument with the
004228 ** contents of the decoded record.
004229 */
004230 void sqlite3VdbeRecordUnpack(
004231 KeyInfo *pKeyInfo, /* Information about the record format */
004232 int nKey, /* Size of the binary record */
004233 const void *pKey, /* The binary record */
004234 UnpackedRecord *p /* Populate this structure before returning. */
004235 ){
004236 const unsigned char *aKey = (const unsigned char *)pKey;
004237 u32 d;
004238 u32 idx; /* Offset in aKey[] to read from */
004239 u16 u; /* Unsigned loop counter */
004240 u32 szHdr;
004241 Mem *pMem = p->aMem;
004242
004243 p->default_rc = 0;
004244 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
004245 idx = getVarint32(aKey, szHdr);
004246 d = szHdr;
004247 u = 0;
004248 while( idx<szHdr && d<=(u32)nKey ){
004249 u32 serial_type;
004250
004251 idx += getVarint32(&aKey[idx], serial_type);
004252 pMem->enc = pKeyInfo->enc;
004253 pMem->db = pKeyInfo->db;
004254 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
004255 pMem->szMalloc = 0;
004256 pMem->z = 0;
004257 sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
004258 d += sqlite3VdbeSerialTypeLen(serial_type);
004259 pMem++;
004260 if( (++u)>=p->nField ) break;
004261 }
004262 if( d>(u32)nKey && u ){
004263 assert( CORRUPT_DB );
004264 /* In a corrupt record entry, the last pMem might have been set up using
004265 ** uninitialized memory. Overwrite its value with NULL, to prevent
004266 ** warnings from MSAN. */
004267 sqlite3VdbeMemSetNull(pMem-1);
004268 }
004269 assert( u<=pKeyInfo->nKeyField + 1 );
004270 p->nField = u;
004271 }
004272
004273 #ifdef SQLITE_DEBUG
004274 /*
004275 ** This function compares two index or table record keys in the same way
004276 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
004277 ** this function deserializes and compares values using the
004278 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
004279 ** in assert() statements to ensure that the optimized code in
004280 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
004281 **
004282 ** Return true if the result of comparison is equivalent to desiredResult.
004283 ** Return false if there is a disagreement.
004284 */
004285 static int vdbeRecordCompareDebug(
004286 int nKey1, const void *pKey1, /* Left key */
004287 const UnpackedRecord *pPKey2, /* Right key */
004288 int desiredResult /* Correct answer */
004289 ){
004290 u32 d1; /* Offset into aKey[] of next data element */
004291 u32 idx1; /* Offset into aKey[] of next header element */
004292 u32 szHdr1; /* Number of bytes in header */
004293 int i = 0;
004294 int rc = 0;
004295 const unsigned char *aKey1 = (const unsigned char *)pKey1;
004296 KeyInfo *pKeyInfo;
004297 Mem mem1;
004298
004299 pKeyInfo = pPKey2->pKeyInfo;
004300 if( pKeyInfo->db==0 ) return 1;
004301 mem1.enc = pKeyInfo->enc;
004302 mem1.db = pKeyInfo->db;
004303 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
004304 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
004305
004306 /* Compilers may complain that mem1.u.i is potentially uninitialized.
004307 ** We could initialize it, as shown here, to silence those complaints.
004308 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
004309 ** the unnecessary initialization has a measurable negative performance
004310 ** impact, since this routine is a very high runner. And so, we choose
004311 ** to ignore the compiler warnings and leave this variable uninitialized.
004312 */
004313 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
004314
004315 idx1 = getVarint32(aKey1, szHdr1);
004316 if( szHdr1>98307 ) return SQLITE_CORRUPT;
004317 d1 = szHdr1;
004318 assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
004319 assert( pKeyInfo->aSortFlags!=0 );
004320 assert( pKeyInfo->nKeyField>0 );
004321 assert( idx1<=szHdr1 || CORRUPT_DB );
004322 do{
004323 u32 serial_type1;
004324
004325 /* Read the serial types for the next element in each key. */
004326 idx1 += getVarint32( aKey1+idx1, serial_type1 );
004327
004328 /* Verify that there is enough key space remaining to avoid
004329 ** a buffer overread. The "d1+serial_type1+2" subexpression will
004330 ** always be greater than or equal to the amount of required key space.
004331 ** Use that approximation to avoid the more expensive call to
004332 ** sqlite3VdbeSerialTypeLen() in the common case.
004333 */
004334 if( d1+(u64)serial_type1+2>(u64)nKey1
004335 && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
004336 ){
004337 if( serial_type1>=1
004338 && serial_type1<=7
004339 && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)<=(u64)nKey1+8
004340 && CORRUPT_DB
004341 ){
004342 return 1; /* corrupt record not detected by
004343 ** sqlite3VdbeRecordCompareWithSkip(). Return true
004344 ** to avoid firing the assert() */
004345 }
004346 break;
004347 }
004348
004349 /* Extract the values to be compared.
004350 */
004351 sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
004352 d1 += sqlite3VdbeSerialTypeLen(serial_type1);
004353
004354 /* Do the comparison
004355 */
004356 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
004357 pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
004358 if( rc!=0 ){
004359 assert( mem1.szMalloc==0 ); /* See comment below */
004360 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
004361 && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
004362 ){
004363 rc = -rc;
004364 }
004365 if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
004366 rc = -rc; /* Invert the result for DESC sort order. */
004367 }
004368 goto debugCompareEnd;
004369 }
004370 i++;
004371 }while( idx1<szHdr1 && i<pPKey2->nField );
004372
004373 /* No memory allocation is ever used on mem1. Prove this using
004374 ** the following assert(). If the assert() fails, it indicates a
004375 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
004376 */
004377 assert( mem1.szMalloc==0 );
004378
004379 /* rc==0 here means that one of the keys ran out of fields and
004380 ** all the fields up to that point were equal. Return the default_rc
004381 ** value. */
004382 rc = pPKey2->default_rc;
004383
004384 debugCompareEnd:
004385 if( desiredResult==0 && rc==0 ) return 1;
004386 if( desiredResult<0 && rc<0 ) return 1;
004387 if( desiredResult>0 && rc>0 ) return 1;
004388 if( CORRUPT_DB ) return 1;
004389 if( pKeyInfo->db->mallocFailed ) return 1;
004390 return 0;
004391 }
004392 #endif
004393
004394 #ifdef SQLITE_DEBUG
004395 /*
004396 ** Count the number of fields (a.k.a. columns) in the record given by
004397 ** pKey,nKey. The verify that this count is less than or equal to the
004398 ** limit given by pKeyInfo->nAllField.
004399 **
004400 ** If this constraint is not satisfied, it means that the high-speed
004401 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
004402 ** not work correctly. If this assert() ever fires, it probably means
004403 ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
004404 ** incorrectly.
004405 */
004406 static void vdbeAssertFieldCountWithinLimits(
004407 int nKey, const void *pKey, /* The record to verify */
004408 const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
004409 ){
004410 int nField = 0;
004411 u32 szHdr;
004412 u32 idx;
004413 u32 notUsed;
004414 const unsigned char *aKey = (const unsigned char*)pKey;
004415
004416 if( CORRUPT_DB ) return;
004417 idx = getVarint32(aKey, szHdr);
004418 assert( nKey>=0 );
004419 assert( szHdr<=(u32)nKey );
004420 while( idx<szHdr ){
004421 idx += getVarint32(aKey+idx, notUsed);
004422 nField++;
004423 }
004424 assert( nField <= pKeyInfo->nAllField );
004425 }
004426 #else
004427 # define vdbeAssertFieldCountWithinLimits(A,B,C)
004428 #endif
004429
004430 /*
004431 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
004432 ** using the collation sequence pColl. As usual, return a negative , zero
004433 ** or positive value if *pMem1 is less than, equal to or greater than
004434 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
004435 */
004436 static int vdbeCompareMemString(
004437 const Mem *pMem1,
004438 const Mem *pMem2,
004439 const CollSeq *pColl,
004440 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
004441 ){
004442 if( pMem1->enc==pColl->enc ){
004443 /* The strings are already in the correct encoding. Call the
004444 ** comparison function directly */
004445 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
004446 }else{
004447 int rc;
004448 const void *v1, *v2;
004449 Mem c1;
004450 Mem c2;
004451 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
004452 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
004453 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
004454 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
004455 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
004456 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
004457 if( (v1==0 || v2==0) ){
004458 if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
004459 rc = 0;
004460 }else{
004461 rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
004462 }
004463 sqlite3VdbeMemReleaseMalloc(&c1);
004464 sqlite3VdbeMemReleaseMalloc(&c2);
004465 return rc;
004466 }
004467 }
004468
004469 /*
004470 ** The input pBlob is guaranteed to be a Blob that is not marked
004471 ** with MEM_Zero. Return true if it could be a zero-blob.
004472 */
004473 static int isAllZero(const char *z, int n){
004474 int i;
004475 for(i=0; i<n; i++){
004476 if( z[i] ) return 0;
004477 }
004478 return 1;
004479 }
004480
004481 /*
004482 ** Compare two blobs. Return negative, zero, or positive if the first
004483 ** is less than, equal to, or greater than the second, respectively.
004484 ** If one blob is a prefix of the other, then the shorter is the lessor.
004485 */
004486 SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
004487 int c;
004488 int n1 = pB1->n;
004489 int n2 = pB2->n;
004490
004491 /* It is possible to have a Blob value that has some non-zero content
004492 ** followed by zero content. But that only comes up for Blobs formed
004493 ** by the OP_MakeRecord opcode, and such Blobs never get passed into
004494 ** sqlite3MemCompare(). */
004495 assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
004496 assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
004497
004498 if( (pB1->flags|pB2->flags) & MEM_Zero ){
004499 if( pB1->flags & pB2->flags & MEM_Zero ){
004500 return pB1->u.nZero - pB2->u.nZero;
004501 }else if( pB1->flags & MEM_Zero ){
004502 if( !isAllZero(pB2->z, pB2->n) ) return -1;
004503 return pB1->u.nZero - n2;
004504 }else{
004505 if( !isAllZero(pB1->z, pB1->n) ) return +1;
004506 return n1 - pB2->u.nZero;
004507 }
004508 }
004509 c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
004510 if( c ) return c;
004511 return n1 - n2;
004512 }
004513
004514 /* The following two functions are used only within testcase() to prove
004515 ** test coverage. These functions do no exist for production builds.
004516 ** We must use separate SQLITE_NOINLINE functions here, since otherwise
004517 ** optimizer code movement causes gcov to become very confused.
004518 */
004519 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
004520 static int SQLITE_NOINLINE doubleLt(double a, double b){ return a<b; }
004521 static int SQLITE_NOINLINE doubleEq(double a, double b){ return a==b; }
004522 #endif
004523
004524 /*
004525 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
004526 ** number. Return negative, zero, or positive if the first (i64) is less than,
004527 ** equal to, or greater than the second (double).
004528 */
004529 int sqlite3IntFloatCompare(i64 i, double r){
004530 if( sqlite3IsNaN(r) ){
004531 /* SQLite considers NaN to be a NULL. And all integer values are greater
004532 ** than NULL */
004533 return 1;
004534 }else{
004535 i64 y;
004536 if( r<-9223372036854775808.0 ) return +1;
004537 if( r>=9223372036854775808.0 ) return -1;
004538 y = (i64)r;
004539 if( i<y ) return -1;
004540 if( i>y ) return +1;
004541 testcase( doubleLt(((double)i),r) );
004542 testcase( doubleLt(r,((double)i)) );
004543 testcase( doubleEq(r,((double)i)) );
004544 return (((double)i)<r) ? -1 : (((double)i)>r);
004545 }
004546 }
004547
004548 /*
004549 ** Compare the values contained by the two memory cells, returning
004550 ** negative, zero or positive if pMem1 is less than, equal to, or greater
004551 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
004552 ** and reals) sorted numerically, followed by text ordered by the collating
004553 ** sequence pColl and finally blob's ordered by memcmp().
004554 **
004555 ** Two NULL values are considered equal by this function.
004556 */
004557 int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
004558 int f1, f2;
004559 int combined_flags;
004560
004561 f1 = pMem1->flags;
004562 f2 = pMem2->flags;
004563 combined_flags = f1|f2;
004564 assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
004565
004566 /* If one value is NULL, it is less than the other. If both values
004567 ** are NULL, return 0.
004568 */
004569 if( combined_flags&MEM_Null ){
004570 return (f2&MEM_Null) - (f1&MEM_Null);
004571 }
004572
004573 /* At least one of the two values is a number
004574 */
004575 if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
004576 testcase( combined_flags & MEM_Int );
004577 testcase( combined_flags & MEM_Real );
004578 testcase( combined_flags & MEM_IntReal );
004579 if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
004580 testcase( f1 & f2 & MEM_Int );
004581 testcase( f1 & f2 & MEM_IntReal );
004582 if( pMem1->u.i < pMem2->u.i ) return -1;
004583 if( pMem1->u.i > pMem2->u.i ) return +1;
004584 return 0;
004585 }
004586 if( (f1 & f2 & MEM_Real)!=0 ){
004587 if( pMem1->u.r < pMem2->u.r ) return -1;
004588 if( pMem1->u.r > pMem2->u.r ) return +1;
004589 return 0;
004590 }
004591 if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
004592 testcase( f1 & MEM_Int );
004593 testcase( f1 & MEM_IntReal );
004594 if( (f2&MEM_Real)!=0 ){
004595 return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
004596 }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
004597 if( pMem1->u.i < pMem2->u.i ) return -1;
004598 if( pMem1->u.i > pMem2->u.i ) return +1;
004599 return 0;
004600 }else{
004601 return -1;
004602 }
004603 }
004604 if( (f1&MEM_Real)!=0 ){
004605 if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
004606 testcase( f2 & MEM_Int );
004607 testcase( f2 & MEM_IntReal );
004608 return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
004609 }else{
004610 return -1;
004611 }
004612 }
004613 return +1;
004614 }
004615
004616 /* If one value is a string and the other is a blob, the string is less.
004617 ** If both are strings, compare using the collating functions.
004618 */
004619 if( combined_flags&MEM_Str ){
004620 if( (f1 & MEM_Str)==0 ){
004621 return 1;
004622 }
004623 if( (f2 & MEM_Str)==0 ){
004624 return -1;
004625 }
004626
004627 assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
004628 assert( pMem1->enc==SQLITE_UTF8 ||
004629 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
004630
004631 /* The collation sequence must be defined at this point, even if
004632 ** the user deletes the collation sequence after the vdbe program is
004633 ** compiled (this was not always the case).
004634 */
004635 assert( !pColl || pColl->xCmp );
004636
004637 if( pColl ){
004638 return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
004639 }
004640 /* If a NULL pointer was passed as the collate function, fall through
004641 ** to the blob case and use memcmp(). */
004642 }
004643
004644 /* Both values must be blobs. Compare using memcmp(). */
004645 return sqlite3BlobCompare(pMem1, pMem2);
004646 }
004647
004648
004649 /*
004650 ** The first argument passed to this function is a serial-type that
004651 ** corresponds to an integer - all values between 1 and 9 inclusive
004652 ** except 7. The second points to a buffer containing an integer value
004653 ** serialized according to serial_type. This function deserializes
004654 ** and returns the value.
004655 */
004656 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
004657 u32 y;
004658 assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
004659 switch( serial_type ){
004660 case 0:
004661 case 1:
004662 testcase( aKey[0]&0x80 );
004663 return ONE_BYTE_INT(aKey);
004664 case 2:
004665 testcase( aKey[0]&0x80 );
004666 return TWO_BYTE_INT(aKey);
004667 case 3:
004668 testcase( aKey[0]&0x80 );
004669 return THREE_BYTE_INT(aKey);
004670 case 4: {
004671 testcase( aKey[0]&0x80 );
004672 y = FOUR_BYTE_UINT(aKey);
004673 return (i64)*(int*)&y;
004674 }
004675 case 5: {
004676 testcase( aKey[0]&0x80 );
004677 return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
004678 }
004679 case 6: {
004680 u64 x = FOUR_BYTE_UINT(aKey);
004681 testcase( aKey[0]&0x80 );
004682 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
004683 return (i64)*(i64*)&x;
004684 }
004685 }
004686
004687 return (serial_type - 8);
004688 }
004689
004690 /*
004691 ** This function compares the two table rows or index records
004692 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
004693 ** or positive integer if key1 is less than, equal to or
004694 ** greater than key2. The {nKey1, pKey1} key must be a blob
004695 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
004696 ** key must be a parsed key such as obtained from
004697 ** sqlite3VdbeParseRecord.
004698 **
004699 ** If argument bSkip is non-zero, it is assumed that the caller has already
004700 ** determined that the first fields of the keys are equal.
004701 **
004702 ** Key1 and Key2 do not have to contain the same number of fields. If all
004703 ** fields that appear in both keys are equal, then pPKey2->default_rc is
004704 ** returned.
004705 **
004706 ** If database corruption is discovered, set pPKey2->errCode to
004707 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
004708 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
004709 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
004710 */
004711 int sqlite3VdbeRecordCompareWithSkip(
004712 int nKey1, const void *pKey1, /* Left key */
004713 UnpackedRecord *pPKey2, /* Right key */
004714 int bSkip /* If true, skip the first field */
004715 ){
004716 u32 d1; /* Offset into aKey[] of next data element */
004717 int i; /* Index of next field to compare */
004718 u32 szHdr1; /* Size of record header in bytes */
004719 u32 idx1; /* Offset of first type in header */
004720 int rc = 0; /* Return value */
004721 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
004722 KeyInfo *pKeyInfo;
004723 const unsigned char *aKey1 = (const unsigned char *)pKey1;
004724 Mem mem1;
004725
004726 /* If bSkip is true, then the caller has already determined that the first
004727 ** two elements in the keys are equal. Fix the various stack variables so
004728 ** that this routine begins comparing at the second field. */
004729 if( bSkip ){
004730 u32 s1 = aKey1[1];
004731 if( s1<0x80 ){
004732 idx1 = 2;
004733 }else{
004734 idx1 = 1 + sqlite3GetVarint32(&aKey1[1], &s1);
004735 }
004736 szHdr1 = aKey1[0];
004737 d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
004738 i = 1;
004739 pRhs++;
004740 }else{
004741 if( (szHdr1 = aKey1[0])<0x80 ){
004742 idx1 = 1;
004743 }else{
004744 idx1 = sqlite3GetVarint32(aKey1, &szHdr1);
004745 }
004746 d1 = szHdr1;
004747 i = 0;
004748 }
004749 if( d1>(unsigned)nKey1 ){
004750 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004751 return 0; /* Corruption */
004752 }
004753
004754 VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
004755 assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
004756 || CORRUPT_DB );
004757 assert( pPKey2->pKeyInfo->aSortFlags!=0 );
004758 assert( pPKey2->pKeyInfo->nKeyField>0 );
004759 assert( idx1<=szHdr1 || CORRUPT_DB );
004760 while( 1 /*exit-by-break*/ ){
004761 u32 serial_type;
004762
004763 /* RHS is an integer */
004764 if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
004765 testcase( pRhs->flags & MEM_Int );
004766 testcase( pRhs->flags & MEM_IntReal );
004767 serial_type = aKey1[idx1];
004768 testcase( serial_type==12 );
004769 if( serial_type>=10 ){
004770 rc = serial_type==10 ? -1 : +1;
004771 }else if( serial_type==0 ){
004772 rc = -1;
004773 }else if( serial_type==7 ){
004774 serialGet7(&aKey1[d1], &mem1);
004775 rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
004776 }else{
004777 i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
004778 i64 rhs = pRhs->u.i;
004779 if( lhs<rhs ){
004780 rc = -1;
004781 }else if( lhs>rhs ){
004782 rc = +1;
004783 }
004784 }
004785 }
004786
004787 /* RHS is real */
004788 else if( pRhs->flags & MEM_Real ){
004789 serial_type = aKey1[idx1];
004790 if( serial_type>=10 ){
004791 /* Serial types 12 or greater are strings and blobs (greater than
004792 ** numbers). Types 10 and 11 are currently "reserved for future
004793 ** use", so it doesn't really matter what the results of comparing
004794 ** them to numeric values are. */
004795 rc = serial_type==10 ? -1 : +1;
004796 }else if( serial_type==0 ){
004797 rc = -1;
004798 }else{
004799 if( serial_type==7 ){
004800 if( serialGet7(&aKey1[d1], &mem1) ){
004801 rc = -1; /* mem1 is a NaN */
004802 }else if( mem1.u.r<pRhs->u.r ){
004803 rc = -1;
004804 }else if( mem1.u.r>pRhs->u.r ){
004805 rc = +1;
004806 }else{
004807 assert( rc==0 );
004808 }
004809 }else{
004810 sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
004811 rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
004812 }
004813 }
004814 }
004815
004816 /* RHS is a string */
004817 else if( pRhs->flags & MEM_Str ){
004818 getVarint32NR(&aKey1[idx1], serial_type);
004819 testcase( serial_type==12 );
004820 if( serial_type<12 ){
004821 rc = -1;
004822 }else if( !(serial_type & 0x01) ){
004823 rc = +1;
004824 }else{
004825 mem1.n = (serial_type - 12) / 2;
004826 testcase( (d1+mem1.n)==(unsigned)nKey1 );
004827 testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
004828 if( (d1+mem1.n) > (unsigned)nKey1
004829 || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
004830 ){
004831 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004832 return 0; /* Corruption */
004833 }else if( pKeyInfo->aColl[i] ){
004834 mem1.enc = pKeyInfo->enc;
004835 mem1.db = pKeyInfo->db;
004836 mem1.flags = MEM_Str;
004837 mem1.z = (char*)&aKey1[d1];
004838 rc = vdbeCompareMemString(
004839 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
004840 );
004841 }else{
004842 int nCmp = MIN(mem1.n, pRhs->n);
004843 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
004844 if( rc==0 ) rc = mem1.n - pRhs->n;
004845 }
004846 }
004847 }
004848
004849 /* RHS is a blob */
004850 else if( pRhs->flags & MEM_Blob ){
004851 assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
004852 getVarint32NR(&aKey1[idx1], serial_type);
004853 testcase( serial_type==12 );
004854 if( serial_type<12 || (serial_type & 0x01) ){
004855 rc = -1;
004856 }else{
004857 int nStr = (serial_type - 12) / 2;
004858 testcase( (d1+nStr)==(unsigned)nKey1 );
004859 testcase( (d1+nStr+1)==(unsigned)nKey1 );
004860 if( (d1+nStr) > (unsigned)nKey1 ){
004861 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004862 return 0; /* Corruption */
004863 }else if( pRhs->flags & MEM_Zero ){
004864 if( !isAllZero((const char*)&aKey1[d1],nStr) ){
004865 rc = 1;
004866 }else{
004867 rc = nStr - pRhs->u.nZero;
004868 }
004869 }else{
004870 int nCmp = MIN(nStr, pRhs->n);
004871 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
004872 if( rc==0 ) rc = nStr - pRhs->n;
004873 }
004874 }
004875 }
004876
004877 /* RHS is null */
004878 else{
004879 serial_type = aKey1[idx1];
004880 if( serial_type==0
004881 || serial_type==10
004882 || (serial_type==7 && serialGet7(&aKey1[d1], &mem1)!=0)
004883 ){
004884 assert( rc==0 );
004885 }else{
004886 rc = 1;
004887 }
004888 }
004889
004890 if( rc!=0 ){
004891 int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
004892 if( sortFlags ){
004893 if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
004894 || ((sortFlags & KEYINFO_ORDER_DESC)
004895 !=(serial_type==0 || (pRhs->flags&MEM_Null)))
004896 ){
004897 rc = -rc;
004898 }
004899 }
004900 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
004901 assert( mem1.szMalloc==0 ); /* See comment below */
004902 return rc;
004903 }
004904
004905 i++;
004906 if( i==pPKey2->nField ) break;
004907 pRhs++;
004908 d1 += sqlite3VdbeSerialTypeLen(serial_type);
004909 if( d1>(unsigned)nKey1 ) break;
004910 idx1 += sqlite3VarintLen(serial_type);
004911 if( idx1>=(unsigned)szHdr1 ){
004912 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
004913 return 0; /* Corrupt index */
004914 }
004915 }
004916
004917 /* No memory allocation is ever used on mem1. Prove this using
004918 ** the following assert(). If the assert() fails, it indicates a
004919 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
004920 assert( mem1.szMalloc==0 );
004921
004922 /* rc==0 here means that one or both of the keys ran out of fields and
004923 ** all the fields up to that point were equal. Return the default_rc
004924 ** value. */
004925 assert( CORRUPT_DB
004926 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
004927 || pPKey2->pKeyInfo->db->mallocFailed
004928 );
004929 pPKey2->eqSeen = 1;
004930 return pPKey2->default_rc;
004931 }
004932 int sqlite3VdbeRecordCompare(
004933 int nKey1, const void *pKey1, /* Left key */
004934 UnpackedRecord *pPKey2 /* Right key */
004935 ){
004936 return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
004937 }
004938
004939
004940 /*
004941 ** This function is an optimized version of sqlite3VdbeRecordCompare()
004942 ** that (a) the first field of pPKey2 is an integer, and (b) the
004943 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
004944 ** byte (i.e. is less than 128).
004945 **
004946 ** To avoid concerns about buffer overreads, this routine is only used
004947 ** on schemas where the maximum valid header size is 63 bytes or less.
004948 */
004949 static int vdbeRecordCompareInt(
004950 int nKey1, const void *pKey1, /* Left key */
004951 UnpackedRecord *pPKey2 /* Right key */
004952 ){
004953 const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
004954 int serial_type = ((const u8*)pKey1)[1];
004955 int res;
004956 u32 y;
004957 u64 x;
004958 i64 v;
004959 i64 lhs;
004960
004961 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
004962 assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
004963 switch( serial_type ){
004964 case 1: { /* 1-byte signed integer */
004965 lhs = ONE_BYTE_INT(aKey);
004966 testcase( lhs<0 );
004967 break;
004968 }
004969 case 2: { /* 2-byte signed integer */
004970 lhs = TWO_BYTE_INT(aKey);
004971 testcase( lhs<0 );
004972 break;
004973 }
004974 case 3: { /* 3-byte signed integer */
004975 lhs = THREE_BYTE_INT(aKey);
004976 testcase( lhs<0 );
004977 break;
004978 }
004979 case 4: { /* 4-byte signed integer */
004980 y = FOUR_BYTE_UINT(aKey);
004981 lhs = (i64)*(int*)&y;
004982 testcase( lhs<0 );
004983 break;
004984 }
004985 case 5: { /* 6-byte signed integer */
004986 lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
004987 testcase( lhs<0 );
004988 break;
004989 }
004990 case 6: { /* 8-byte signed integer */
004991 x = FOUR_BYTE_UINT(aKey);
004992 x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
004993 lhs = *(i64*)&x;
004994 testcase( lhs<0 );
004995 break;
004996 }
004997 case 8:
004998 lhs = 0;
004999 break;
005000 case 9:
005001 lhs = 1;
005002 break;
005003
005004 /* This case could be removed without changing the results of running
005005 ** this code. Including it causes gcc to generate a faster switch
005006 ** statement (since the range of switch targets now starts at zero and
005007 ** is contiguous) but does not cause any duplicate code to be generated
005008 ** (as gcc is clever enough to combine the two like cases). Other
005009 ** compilers might be similar. */
005010 case 0: case 7:
005011 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
005012
005013 default:
005014 return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
005015 }
005016
005017 assert( pPKey2->u.i == pPKey2->aMem[0].u.i );
005018 v = pPKey2->u.i;
005019 if( v>lhs ){
005020 res = pPKey2->r1;
005021 }else if( v<lhs ){
005022 res = pPKey2->r2;
005023 }else if( pPKey2->nField>1 ){
005024 /* The first fields of the two keys are equal. Compare the trailing
005025 ** fields. */
005026 res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
005027 }else{
005028 /* The first fields of the two keys are equal and there are no trailing
005029 ** fields. Return pPKey2->default_rc in this case. */
005030 res = pPKey2->default_rc;
005031 pPKey2->eqSeen = 1;
005032 }
005033
005034 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
005035 return res;
005036 }
005037
005038 /*
005039 ** This function is an optimized version of sqlite3VdbeRecordCompare()
005040 ** that (a) the first field of pPKey2 is a string, that (b) the first field
005041 ** uses the collation sequence BINARY and (c) that the size-of-header varint
005042 ** at the start of (pKey1/nKey1) fits in a single byte.
005043 */
005044 static int vdbeRecordCompareString(
005045 int nKey1, const void *pKey1, /* Left key */
005046 UnpackedRecord *pPKey2 /* Right key */
005047 ){
005048 const u8 *aKey1 = (const u8*)pKey1;
005049 int serial_type;
005050 int res;
005051
005052 assert( pPKey2->aMem[0].flags & MEM_Str );
005053 assert( pPKey2->aMem[0].n == pPKey2->n );
005054 assert( pPKey2->aMem[0].z == pPKey2->u.z );
005055 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
005056 serial_type = (signed char)(aKey1[1]);
005057
005058 vrcs_restart:
005059 if( serial_type<12 ){
005060 if( serial_type<0 ){
005061 sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);
005062 if( serial_type>=12 ) goto vrcs_restart;
005063 assert( CORRUPT_DB );
005064 }
005065 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
005066 }else if( !(serial_type & 0x01) ){
005067 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
005068 }else{
005069 int nCmp;
005070 int nStr;
005071 int szHdr = aKey1[0];
005072
005073 nStr = (serial_type-12) / 2;
005074 if( (szHdr + nStr) > nKey1 ){
005075 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
005076 return 0; /* Corruption */
005077 }
005078 nCmp = MIN( pPKey2->n, nStr );
005079 res = memcmp(&aKey1[szHdr], pPKey2->u.z, nCmp);
005080
005081 if( res>0 ){
005082 res = pPKey2->r2;
005083 }else if( res<0 ){
005084 res = pPKey2->r1;
005085 }else{
005086 res = nStr - pPKey2->n;
005087 if( res==0 ){
005088 if( pPKey2->nField>1 ){
005089 res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
005090 }else{
005091 res = pPKey2->default_rc;
005092 pPKey2->eqSeen = 1;
005093 }
005094 }else if( res>0 ){
005095 res = pPKey2->r2;
005096 }else{
005097 res = pPKey2->r1;
005098 }
005099 }
005100 }
005101
005102 assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
005103 || CORRUPT_DB
005104 || pPKey2->pKeyInfo->db->mallocFailed
005105 );
005106 return res;
005107 }
005108
005109 /*
005110 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
005111 ** suitable for comparing serialized records to the unpacked record passed
005112 ** as the only argument.
005113 */
005114 RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
005115 /* varintRecordCompareInt() and varintRecordCompareString() both assume
005116 ** that the size-of-header varint that occurs at the start of each record
005117 ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
005118 ** also assumes that it is safe to overread a buffer by at least the
005119 ** maximum possible legal header size plus 8 bytes. Because there is
005120 ** guaranteed to be at least 74 (but not 136) bytes of padding following each
005121 ** buffer passed to varintRecordCompareInt() this makes it convenient to
005122 ** limit the size of the header to 64 bytes in cases where the first field
005123 ** is an integer.
005124 **
005125 ** The easiest way to enforce this limit is to consider only records with
005126 ** 13 fields or less. If the first field is an integer, the maximum legal
005127 ** header size is (12*5 + 1 + 1) bytes. */
005128 if( p->pKeyInfo->nAllField<=13 ){
005129 int flags = p->aMem[0].flags;
005130 if( p->pKeyInfo->aSortFlags[0] ){
005131 if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
005132 return sqlite3VdbeRecordCompare;
005133 }
005134 p->r1 = 1;
005135 p->r2 = -1;
005136 }else{
005137 p->r1 = -1;
005138 p->r2 = 1;
005139 }
005140 if( (flags & MEM_Int) ){
005141 p->u.i = p->aMem[0].u.i;
005142 return vdbeRecordCompareInt;
005143 }
005144 testcase( flags & MEM_Real );
005145 testcase( flags & MEM_Null );
005146 testcase( flags & MEM_Blob );
005147 if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
005148 && p->pKeyInfo->aColl[0]==0
005149 ){
005150 assert( flags & MEM_Str );
005151 p->u.z = p->aMem[0].z;
005152 p->n = p->aMem[0].n;
005153 return vdbeRecordCompareString;
005154 }
005155 }
005156
005157 return sqlite3VdbeRecordCompare;
005158 }
005159
005160 /*
005161 ** pCur points at an index entry created using the OP_MakeRecord opcode.
005162 ** Read the rowid (the last field in the record) and store it in *rowid.
005163 ** Return SQLITE_OK if everything works, or an error code otherwise.
005164 **
005165 ** pCur might be pointing to text obtained from a corrupt database file.
005166 ** So the content cannot be trusted. Do appropriate checks on the content.
005167 */
005168 int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
005169 i64 nCellKey = 0;
005170 int rc;
005171 u32 szHdr; /* Size of the header */
005172 u32 typeRowid; /* Serial type of the rowid */
005173 u32 lenRowid; /* Size of the rowid */
005174 Mem m, v;
005175
005176 /* Get the size of the index entry. Only indices entries of less
005177 ** than 2GiB are support - anything large must be database corruption.
005178 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
005179 ** this code can safely assume that nCellKey is 32-bits
005180 */
005181 assert( sqlite3BtreeCursorIsValid(pCur) );
005182 nCellKey = sqlite3BtreePayloadSize(pCur);
005183 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
005184
005185 /* Read in the complete content of the index entry */
005186 sqlite3VdbeMemInit(&m, db, 0);
005187 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
005188 if( rc ){
005189 return rc;
005190 }
005191
005192 /* The index entry must begin with a header size */
005193 getVarint32NR((u8*)m.z, szHdr);
005194 testcase( szHdr==3 );
005195 testcase( szHdr==(u32)m.n );
005196 testcase( szHdr>0x7fffffff );
005197 assert( m.n>=0 );
005198 if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
005199 goto idx_rowid_corruption;
005200 }
005201
005202 /* The last field of the index should be an integer - the ROWID.
005203 ** Verify that the last entry really is an integer. */
005204 getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
005205 testcase( typeRowid==1 );
005206 testcase( typeRowid==2 );
005207 testcase( typeRowid==3 );
005208 testcase( typeRowid==4 );
005209 testcase( typeRowid==5 );
005210 testcase( typeRowid==6 );
005211 testcase( typeRowid==8 );
005212 testcase( typeRowid==9 );
005213 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
005214 goto idx_rowid_corruption;
005215 }
005216 lenRowid = sqlite3SmallTypeSizes[typeRowid];
005217 testcase( (u32)m.n==szHdr+lenRowid );
005218 if( unlikely((u32)m.n<szHdr+lenRowid) ){
005219 goto idx_rowid_corruption;
005220 }
005221
005222 /* Fetch the integer off the end of the index record */
005223 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
005224 *rowid = v.u.i;
005225 sqlite3VdbeMemReleaseMalloc(&m);
005226 return SQLITE_OK;
005227
005228 /* Jump here if database corruption is detected after m has been
005229 ** allocated. Free the m object and return SQLITE_CORRUPT. */
005230 idx_rowid_corruption:
005231 testcase( m.szMalloc!=0 );
005232 sqlite3VdbeMemReleaseMalloc(&m);
005233 return SQLITE_CORRUPT_BKPT;
005234 }
005235
005236 /*
005237 ** Compare the key of the index entry that cursor pC is pointing to against
005238 ** the key string in pUnpacked. Write into *pRes a number
005239 ** that is negative, zero, or positive if pC is less than, equal to,
005240 ** or greater than pUnpacked. Return SQLITE_OK on success.
005241 **
005242 ** pUnpacked is either created without a rowid or is truncated so that it
005243 ** omits the rowid at the end. The rowid at the end of the index entry
005244 ** is ignored as well. Hence, this routine only compares the prefixes
005245 ** of the keys prior to the final rowid, not the entire key.
005246 */
005247 int sqlite3VdbeIdxKeyCompare(
005248 sqlite3 *db, /* Database connection */
005249 VdbeCursor *pC, /* The cursor to compare against */
005250 UnpackedRecord *pUnpacked, /* Unpacked version of key */
005251 int *res /* Write the comparison result here */
005252 ){
005253 i64 nCellKey = 0;
005254 int rc;
005255 BtCursor *pCur;
005256 Mem m;
005257
005258 assert( pC->eCurType==CURTYPE_BTREE );
005259 pCur = pC->uc.pCursor;
005260 assert( sqlite3BtreeCursorIsValid(pCur) );
005261 nCellKey = sqlite3BtreePayloadSize(pCur);
005262 /* nCellKey will always be between 0 and 0xffffffff because of the way
005263 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
005264 if( nCellKey<=0 || nCellKey>0x7fffffff ){
005265 *res = 0;
005266 return SQLITE_CORRUPT_BKPT;
005267 }
005268 sqlite3VdbeMemInit(&m, db, 0);
005269 rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
005270 if( rc ){
005271 return rc;
005272 }
005273 *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
005274 sqlite3VdbeMemReleaseMalloc(&m);
005275 return SQLITE_OK;
005276 }
005277
005278 /*
005279 ** This routine sets the value to be returned by subsequent calls to
005280 ** sqlite3_changes() on the database handle 'db'.
005281 */
005282 void sqlite3VdbeSetChanges(sqlite3 *db, i64 nChange){
005283 assert( sqlite3_mutex_held(db->mutex) );
005284 db->nChange = nChange;
005285 db->nTotalChange += nChange;
005286 }
005287
005288 /*
005289 ** Set a flag in the vdbe to update the change counter when it is finalised
005290 ** or reset.
005291 */
005292 void sqlite3VdbeCountChanges(Vdbe *v){
005293 v->changeCntOn = 1;
005294 }
005295
005296 /*
005297 ** Mark every prepared statement associated with a database connection
005298 ** as expired.
005299 **
005300 ** An expired statement means that recompilation of the statement is
005301 ** recommend. Statements expire when things happen that make their
005302 ** programs obsolete. Removing user-defined functions or collating
005303 ** sequences, or changing an authorization function are the types of
005304 ** things that make prepared statements obsolete.
005305 **
005306 ** If iCode is 1, then expiration is advisory. The statement should
005307 ** be reprepared before being restarted, but if it is already running
005308 ** it is allowed to run to completion.
005309 **
005310 ** Internally, this function just sets the Vdbe.expired flag on all
005311 ** prepared statements. The flag is set to 1 for an immediate expiration
005312 ** and set to 2 for an advisory expiration.
005313 */
005314 void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
005315 Vdbe *p;
005316 for(p = db->pVdbe; p; p=p->pVNext){
005317 p->expired = iCode+1;
005318 }
005319 }
005320
005321 /*
005322 ** Return the database associated with the Vdbe.
005323 */
005324 sqlite3 *sqlite3VdbeDb(Vdbe *v){
005325 return v->db;
005326 }
005327
005328 /*
005329 ** Return the SQLITE_PREPARE flags for a Vdbe.
005330 */
005331 u8 sqlite3VdbePrepareFlags(Vdbe *v){
005332 return v->prepFlags;
005333 }
005334
005335 /*
005336 ** Return a pointer to an sqlite3_value structure containing the value bound
005337 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
005338 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
005339 ** constants) to the value before returning it.
005340 **
005341 ** The returned value must be freed by the caller using sqlite3ValueFree().
005342 */
005343 sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
005344 assert( iVar>0 );
005345 if( v ){
005346 Mem *pMem = &v->aVar[iVar-1];
005347 assert( (v->db->flags & SQLITE_EnableQPSG)==0
005348 || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
005349 if( 0==(pMem->flags & MEM_Null) ){
005350 sqlite3_value *pRet = sqlite3ValueNew(v->db);
005351 if( pRet ){
005352 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
005353 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
005354 }
005355 return pRet;
005356 }
005357 }
005358 return 0;
005359 }
005360
005361 /*
005362 ** Configure SQL variable iVar so that binding a new value to it signals
005363 ** to sqlite3_reoptimize() that re-preparing the statement may result
005364 ** in a better query plan.
005365 */
005366 void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
005367 assert( iVar>0 );
005368 assert( (v->db->flags & SQLITE_EnableQPSG)==0
005369 || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
005370 if( iVar>=32 ){
005371 v->expmask |= 0x80000000;
005372 }else{
005373 v->expmask |= ((u32)1 << (iVar-1));
005374 }
005375 }
005376
005377 /*
005378 ** Cause a function to throw an error if it was call from OP_PureFunc
005379 ** rather than OP_Function.
005380 **
005381 ** OP_PureFunc means that the function must be deterministic, and should
005382 ** throw an error if it is given inputs that would make it non-deterministic.
005383 ** This routine is invoked by date/time functions that use non-deterministic
005384 ** features such as 'now'.
005385 */
005386 int sqlite3NotPureFunc(sqlite3_context *pCtx){
005387 const VdbeOp *pOp;
005388 #ifdef SQLITE_ENABLE_STAT4
005389 if( pCtx->pVdbe==0 ) return 1;
005390 #endif
005391 pOp = pCtx->pVdbe->aOp + pCtx->iOp;
005392 if( pOp->opcode==OP_PureFunc ){
005393 const char *zContext;
005394 char *zMsg;
005395 if( pOp->p5 & NC_IsCheck ){
005396 zContext = "a CHECK constraint";
005397 }else if( pOp->p5 & NC_GenCol ){
005398 zContext = "a generated column";
005399 }else{
005400 zContext = "an index";
005401 }
005402 zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
005403 pCtx->pFunc->zName, zContext);
005404 sqlite3_result_error(pCtx, zMsg, -1);
005405 sqlite3_free(zMsg);
005406 return 0;
005407 }
005408 return 1;
005409 }
005410
005411 #if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
005412 /*
005413 ** This Walker callback is used to help verify that calls to
005414 ** sqlite3BtreeCursorHint() with opcode BTREE_HINT_RANGE have
005415 ** byte-code register values correctly initialized.
005416 */
005417 int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr){
005418 if( pExpr->op==TK_REGISTER ){
005419 assert( (pWalker->u.aMem[pExpr->iTable].flags & MEM_Undefined)==0 );
005420 }
005421 return WRC_Continue;
005422 }
005423 #endif /* SQLITE_ENABLE_CURSOR_HINTS && SQLITE_DEBUG */
005424
005425 #ifndef SQLITE_OMIT_VIRTUALTABLE
005426 /*
005427 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
005428 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
005429 ** in memory obtained from sqlite3DbMalloc).
005430 */
005431 void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
005432 if( pVtab->zErrMsg ){
005433 sqlite3 *db = p->db;
005434 sqlite3DbFree(db, p->zErrMsg);
005435 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
005436 sqlite3_free(pVtab->zErrMsg);
005437 pVtab->zErrMsg = 0;
005438 }
005439 }
005440 #endif /* SQLITE_OMIT_VIRTUALTABLE */
005441
005442 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
005443
005444 /*
005445 ** If the second argument is not NULL, release any allocations associated
005446 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
005447 ** structure itself, using sqlite3DbFree().
005448 **
005449 ** This function is used to free UnpackedRecord structures allocated by
005450 ** the vdbeUnpackRecord() function found in vdbeapi.c.
005451 */
005452 static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
005453 assert( db!=0 );
005454 if( p ){
005455 int i;
005456 for(i=0; i<nField; i++){
005457 Mem *pMem = &p->aMem[i];
005458 if( pMem->zMalloc ) sqlite3VdbeMemReleaseMalloc(pMem);
005459 }
005460 sqlite3DbNNFreeNN(db, p);
005461 }
005462 }
005463 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
005464
005465 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
005466 /*
005467 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
005468 ** then cursor passed as the second argument should point to the row about
005469 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
005470 ** the required value will be read from the row the cursor points to.
005471 */
005472 void sqlite3VdbePreUpdateHook(
005473 Vdbe *v, /* Vdbe pre-update hook is invoked by */
005474 VdbeCursor *pCsr, /* Cursor to grab old.* values from */
005475 int op, /* SQLITE_INSERT, UPDATE or DELETE */
005476 const char *zDb, /* Database name */
005477 Table *pTab, /* Modified table */
005478 i64 iKey1, /* Initial key value */
005479 int iReg, /* Register for new.* record */
005480 int iBlobWrite
005481 ){
005482 sqlite3 *db = v->db;
005483 i64 iKey2;
005484 PreUpdate preupdate;
005485 const char *zTbl = pTab->zName;
005486 static const u8 fakeSortOrder = 0;
005487 #ifdef SQLITE_DEBUG
005488 int nRealCol;
005489 if( pTab->tabFlags & TF_WithoutRowid ){
005490 nRealCol = sqlite3PrimaryKeyIndex(pTab)->nColumn;
005491 }else if( pTab->tabFlags & TF_HasVirtual ){
005492 nRealCol = pTab->nNVCol;
005493 }else{
005494 nRealCol = pTab->nCol;
005495 }
005496 #endif
005497
005498 assert( db->pPreUpdate==0 );
005499 memset(&preupdate, 0, sizeof(PreUpdate));
005500 if( HasRowid(pTab)==0 ){
005501 iKey1 = iKey2 = 0;
005502 preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
005503 }else{
005504 if( op==SQLITE_UPDATE ){
005505 iKey2 = v->aMem[iReg].u.i;
005506 }else{
005507 iKey2 = iKey1;
005508 }
005509 }
005510
005511 assert( pCsr!=0 );
005512 assert( pCsr->eCurType==CURTYPE_BTREE );
005513 assert( pCsr->nField==nRealCol
005514 || (pCsr->nField==nRealCol+1 && op==SQLITE_DELETE && iReg==-1)
005515 );
005516
005517 preupdate.v = v;
005518 preupdate.pCsr = pCsr;
005519 preupdate.op = op;
005520 preupdate.iNewReg = iReg;
005521 preupdate.keyinfo.db = db;
005522 preupdate.keyinfo.enc = ENC(db);
005523 preupdate.keyinfo.nKeyField = pTab->nCol;
005524 preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
005525 preupdate.iKey1 = iKey1;
005526 preupdate.iKey2 = iKey2;
005527 preupdate.pTab = pTab;
005528 preupdate.iBlobWrite = iBlobWrite;
005529
005530 db->pPreUpdate = &preupdate;
005531 db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
005532 db->pPreUpdate = 0;
005533 sqlite3DbFree(db, preupdate.aRecord);
005534 vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
005535 vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
005536 sqlite3VdbeMemRelease(&preupdate.oldipk);
005537 if( preupdate.aNew ){
005538 int i;
005539 for(i=0; i<pCsr->nField; i++){
005540 sqlite3VdbeMemRelease(&preupdate.aNew[i]);
005541 }
005542 sqlite3DbNNFreeNN(db, preupdate.aNew);
005543 }
005544 if( preupdate.apDflt ){
005545 int i;
005546 for(i=0; i<pTab->nCol; i++){
005547 sqlite3ValueFree(preupdate.apDflt[i]);
005548 }
005549 sqlite3DbFree(db, preupdate.apDflt);
005550 }
005551 }
005552 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */