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