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