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