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