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