AryaWu/sqlite
0
1/*2** 2003 September 63**4** The author disclaims copyright to this source code. In place of5** 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 populating13** 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 */19static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);20static void vdbeFreeOpArray(sqlite3 *, Op *, int);21 22/*23** Create a new virtual database engine.24*/25Vdbe *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->ppVPrev = &p->pVNext;34 }35 p->pVNext = db->pVdbe;36 p->ppVPrev = &db->pVdbe;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*/52Parse *sqlite3VdbeParser(Vdbe *p){53 return p->pParse;54}55 56/*57** Change the error string stored in Vdbe.zErrMsg58*/59void 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*/70void 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_NORMALIZE81/*82** Add a new element to the Vdbe->pDblStr list.83*/84void 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#endif97 98#ifdef SQLITE_ENABLE_NORMALIZE99/*100** zId of length nId is a double-quoted identifier. Check to see if101** that identifier is really used as a string literal.102*/103int 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#endif116 117/*118** Swap byte-code between two VDBE structures.119**120** This happens after pB was previously run and returned121** SQLITE_SCHEMA. The statement was then reprepared in pA.122** This routine transfers the new bytecode in pA over to pB123** so that pB can be run again. The old pB byte code is124** moved back to pA so that it will be cleaned up when pA is125** finalized.126*/127void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){128 Vdbe tmp, *pTmp, **ppTmp;129 char *zTmp;130 assert( pA->db==pB->db );131 tmp = *pA;132 *pA = *pB;133 *pB = tmp;134 pTmp = pA->pVNext;135 pA->pVNext = pB->pVNext;136 pB->pVNext = pTmp;137 ppTmp = pA->ppVPrev;138 pA->ppVPrev = pB->ppVPrev;139 pB->ppVPrev = ppTmp;140 zTmp = pA->zSql;141 pA->zSql = pB->zSql;142 pB->zSql = zTmp;143#ifdef SQLITE_ENABLE_NORMALIZE144 zTmp = pA->zNormSql;145 pA->zNormSql = pB->zNormSql;146 pB->zNormSql = zTmp;147#endif148 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 larger156** than its current size. nOp is guaranteed to be less than or equal157** to 1024/sizeof(Op).158**159** If an out-of-memory error occurs while resizing the array, return160** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain161** unchanged (this is so that any opcodes already allocated can be162** correctly deallocated along with the rest of the Vdbe).163*/164static 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 force169 ** more frequent reallocs and hence provide more opportunities for170 ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used171 ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array172 ** by the minimum* amount required until the size reaches 512. Normal173 ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current174 ** size of the op array or add 1KB of space, whichever is smaller. */175#ifdef SQLITE_TEST_REALLOC_STRESS176 sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc177 : (sqlite3_int64)v->nOpAlloc+nOp);178#else179 sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc180 : (sqlite3_int64)(1024/sizeof(Op)));181 UNUSED_PARAMETER(nOp);182#endif183 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_DEBUG202/* This routine is just a convenient place to set a breakpoint that will203** fire after each opcode is inserted and displayed using204** "PRAGMA vdbe_addoptrace=on". Parameters "pc" (program counter) and205** 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*/213static void test_addop_breakpoint(int pc, Op *pOp){214 static u64 n = 0;215 (void)pc;216 (void)pOp;217 n++;218 if( n==LARGEST_UINT64 ) abort(); /* so that n is used, preventing a warning */219}220#endif221 222/*223** Slow paths for sqlite3VdbeAddOp3() and sqlite3VdbeAddOp4Int() for the224** unusual case when we need to increase the size of the Vdbe.aOp[] array225** before adding the new opcode.226*/227static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){228 assert( p->nOpAlloc<=p->nOp );229 if( growOpArray(p, 1) ) return 1;230 assert( p->nOpAlloc>p->nOp );231 return sqlite3VdbeAddOp3(p, op, p1, p2, p3);232}233static SQLITE_NOINLINE int addOp4IntSlow(234 Vdbe *p, /* Add the opcode to this VM */235 int op, /* The new opcode */236 int p1, /* The P1 operand */237 int p2, /* The P2 operand */238 int p3, /* The P3 operand */239 int p4 /* The P4 operand as an integer */240){241 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);242 if( p->db->mallocFailed==0 ){243 VdbeOp *pOp = &p->aOp[addr];244 pOp->p4type = P4_INT32;245 pOp->p4.i = p4;246 }247 return addr;248}249 250 251/*252** Add a new instruction to the list of instructions current in the253** VDBE. Return the address of the new instruction.254**255** Parameters:256**257** p Pointer to the VDBE258**259** op The opcode for this instruction260**261** p1, p2, p3, p4 Operands262*/263int sqlite3VdbeAddOp0(Vdbe *p, int op){264 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);265}266int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){267 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);268}269int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){270 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);271}272int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){273 int i;274 VdbeOp *pOp;275 276 i = p->nOp;277 assert( p->eVdbeState==VDBE_INIT_STATE );278 assert( op>=0 && op<0xff );279 if( p->nOpAlloc<=i ){280 return growOp3(p, op, p1, p2, p3);281 }282 assert( p->aOp!=0 );283 p->nOp++;284 pOp = &p->aOp[i];285 assert( pOp!=0 );286 pOp->opcode = (u8)op;287 pOp->p5 = 0;288 pOp->p1 = p1;289 pOp->p2 = p2;290 pOp->p3 = p3;291 pOp->p4.p = 0;292 pOp->p4type = P4_NOTUSED;293 294 /* Replicate this logic in sqlite3VdbeAddOp4Int()295 ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */296#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS297 pOp->zComment = 0;298#endif299#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)300 pOp->nExec = 0;301 pOp->nCycle = 0;302#endif303#ifdef SQLITE_DEBUG304 if( p->db->flags & SQLITE_VdbeAddopTrace ){305 sqlite3VdbePrintOp(0, i, &p->aOp[i]);306 test_addop_breakpoint(i, &p->aOp[i]);307 }308#endif309#ifdef SQLITE_VDBE_COVERAGE310 pOp->iSrcLine = 0;311#endif312 /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^313 ** Replicate in sqlite3VdbeAddOp4Int() */314 315 return i;316}317int sqlite3VdbeAddOp4Int(318 Vdbe *p, /* Add the opcode to this VM */319 int op, /* The new opcode */320 int p1, /* The P1 operand */321 int p2, /* The P2 operand */322 int p3, /* The P3 operand */323 int p4 /* The P4 operand as an integer */324){325 int i;326 VdbeOp *pOp;327 328 i = p->nOp;329 if( p->nOpAlloc<=i ){330 return addOp4IntSlow(p, op, p1, p2, p3, p4);331 }332 p->nOp++;333 pOp = &p->aOp[i];334 assert( pOp!=0 );335 pOp->opcode = (u8)op;336 pOp->p5 = 0;337 pOp->p1 = p1;338 pOp->p2 = p2;339 pOp->p3 = p3;340 pOp->p4.i = p4;341 pOp->p4type = P4_INT32;342 343 /* Replicate this logic in sqlite3VdbeAddOp3()344 ** vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */345#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS346 pOp->zComment = 0;347#endif348#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || defined(VDBE_PROFILE)349 pOp->nExec = 0;350 pOp->nCycle = 0;351#endif352#ifdef SQLITE_DEBUG353 if( p->db->flags & SQLITE_VdbeAddopTrace ){354 sqlite3VdbePrintOp(0, i, &p->aOp[i]);355 test_addop_breakpoint(i, &p->aOp[i]);356 }357#endif358#ifdef SQLITE_VDBE_COVERAGE359 pOp->iSrcLine = 0;360#endif361 /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^362 ** Replicate in sqlite3VdbeAddOp3() */363 364 return i;365}366 367/* Generate code for an unconditional jump to instruction iDest368*/369int sqlite3VdbeGoto(Vdbe *p, int iDest){370 return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);371}372 373/* Generate code to cause the string zStr to be loaded into374** register iDest375*/376int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){377 return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);378}379 380/*381** Generate code that initializes multiple registers to string or integer382** constants. The registers begin with iDest and increase consecutively.383** One register is initialized for each characgter in zTypes[]. For each384** "s" character in zTypes[], the register is a string if the argument is385** not NULL, or OP_Null if the value is a null pointer. For each "i" character386** in zTypes[], the register is initialized to an integer.387**388** If the input string does not end with "X" then an OP_ResultRow instruction389** is generated for the values inserted.390*/391void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){392 va_list ap;393 int i;394 char c;395 va_start(ap, zTypes);396 for(i=0; (c = zTypes[i])!=0; i++){397 if( c=='s' ){398 const char *z = va_arg(ap, const char*);399 sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);400 }else if( c=='i' ){401 sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);402 }else{403 goto skip_op_resultrow;404 }405 }406 sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);407skip_op_resultrow:408 va_end(ap);409}410 411/*412** Add an opcode that includes the p4 value as a pointer.413*/414int sqlite3VdbeAddOp4(415 Vdbe *p, /* Add the opcode to this VM */416 int op, /* The new opcode */417 int p1, /* The P1 operand */418 int p2, /* The P2 operand */419 int p3, /* The P3 operand */420 const char *zP4, /* The P4 operand */421 int p4type /* P4 operand type */422){423 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);424 sqlite3VdbeChangeP4(p, addr, zP4, p4type);425 return addr;426}427 428/*429** Add an OP_Function or OP_PureFunc opcode.430**431** The eCallCtx argument is information (typically taken from Expr.op2)432** that describes the calling context of the function. 0 means a general433** function call. NC_IsCheck means called by a check constraint,434** NC_IdxExpr means called as part of an index expression. NC_PartIdx435** means in the WHERE clause of a partial index. NC_GenCol means called436** while computing a generated column value. 0 is the usual case.437*/438int sqlite3VdbeAddFunctionCall(439 Parse *pParse, /* Parsing context */440 int p1, /* Constant argument mask */441 int p2, /* First argument register */442 int p3, /* Register into which results are written */443 int nArg, /* Number of argument */444 const FuncDef *pFunc, /* The function to be invoked */445 int eCallCtx /* Calling context */446){447 Vdbe *v = pParse->pVdbe;448 int addr;449 sqlite3_context *pCtx;450 assert( v );451 pCtx = sqlite3DbMallocRawNN(pParse->db, SZ_CONTEXT(nArg));452 if( pCtx==0 ){453 assert( pParse->db->mallocFailed );454 freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);455 return 0;456 }457 pCtx->pOut = 0;458 pCtx->pFunc = (FuncDef*)pFunc;459 pCtx->pVdbe = 0;460 pCtx->isError = 0;461 pCtx->argc = nArg;462 pCtx->iOp = sqlite3VdbeCurrentAddr(v);463 addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,464 p1, p2, p3, (char*)pCtx, P4_FUNCCTX);465 sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);466 sqlite3MayAbort(pParse);467 return addr;468}469 470/*471** Add an opcode that includes the p4 value with a P4_INT64 or472** P4_REAL type.473*/474int sqlite3VdbeAddOp4Dup8(475 Vdbe *p, /* Add the opcode to this VM */476 int op, /* The new opcode */477 int p1, /* The P1 operand */478 int p2, /* The P2 operand */479 int p3, /* The P3 operand */480 const u8 *zP4, /* The P4 operand */481 int p4type /* P4 operand type */482){483 char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);484 if( p4copy ) memcpy(p4copy, zP4, 8);485 return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);486}487 488#ifndef SQLITE_OMIT_EXPLAIN489/*490** Return the address of the current EXPLAIN QUERY PLAN baseline.491** 0 means "none".492*/493int sqlite3VdbeExplainParent(Parse *pParse){494 VdbeOp *pOp;495 if( pParse->addrExplain==0 ) return 0;496 pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);497 return pOp->p2;498}499 500/*501** Set a debugger breakpoint on the following routine in order to502** monitor the EXPLAIN QUERY PLAN code generation.503*/504#if defined(SQLITE_DEBUG)505void sqlite3ExplainBreakpoint(const char *z1, const char *z2){506 (void)z1;507 (void)z2;508}509#endif510 511/*512** Add a new OP_Explain opcode.513**514** If the bPush flag is true, then make this opcode the parent for515** subsequent Explains until sqlite3VdbeExplainPop() is called.516*/517int sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){518 int addr = 0;519#if !defined(SQLITE_DEBUG)520 /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.521 ** But omit them (for performance) during production builds */522 if( pParse->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )523#endif524 {525 char *zMsg;526 Vdbe *v;527 va_list ap;528 int iThis;529 va_start(ap, zFmt);530 zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);531 va_end(ap);532 v = pParse->pVdbe;533 iThis = v->nOp;534 addr = sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,535 zMsg, P4_DYNAMIC);536 sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetLastOp(v)->p4.z);537 if( bPush){538 pParse->addrExplain = iThis;539 }540 sqlite3VdbeScanStatus(v, iThis, -1, -1, 0, 0);541 }542 return addr;543}544 545/*546** Pop the EXPLAIN QUERY PLAN stack one level.547*/548void sqlite3VdbeExplainPop(Parse *pParse){549 sqlite3ExplainBreakpoint("POP", 0);550 pParse->addrExplain = sqlite3VdbeExplainParent(pParse);551}552#endif /* SQLITE_OMIT_EXPLAIN */553 554/*555** Add an OP_ParseSchema opcode. This routine is broken out from556** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees557** as having been used.558**559** The zWhere string must have been obtained from sqlite3_malloc().560** This routine will take ownership of the allocated memory.561*/562void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere, u16 p5){563 int j;564 sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);565 sqlite3VdbeChangeP5(p, p5);566 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);567 sqlite3MayAbort(p->pParse);568}569 570/* Insert the end of a co-routine571*/572void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){573 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);574 575 /* Clear the temporary register cache, thereby ensuring that each576 ** co-routine has its own independent set of registers, because co-routines577 ** might expect their registers to be preserved across an OP_Yield, and578 ** that could cause problems if two or more co-routines are using the same579 ** temporary register.580 */581 v->pParse->nTempReg = 0;582 v->pParse->nRangeReg = 0;583}584 585/*586** Create a new symbolic label for an instruction that has yet to be587** coded. The symbolic label is really just a negative number. The588** label can be used as the P2 value of an operation. Later, when589** the label is resolved to a specific address, the VDBE will scan590** through its operation list and change all values of P2 which match591** the label into the resolved address.592**593** The VDBE knows that a P2 value is a label because labels are594** always negative and P2 values are suppose to be non-negative.595** Hence, a negative P2 value is a label that has yet to be resolved.596** (Later:) This is only true for opcodes that have the OPFLG_JUMP597** property.598**599** Variable usage notes:600**601** Parse.aLabel[x] Stores the address that the x-th label resolves602** into. For testing (SQLITE_DEBUG), unresolved603** labels stores -1, but that is not required.604** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]605** Parse.nLabel The *negative* of the number of labels that have606** been issued. The negative is stored because607** that gives a performance improvement over storing608** the equivalent positive value.609*/610int sqlite3VdbeMakeLabel(Parse *pParse){611 return --pParse->nLabel;612}613 614/*615** Resolve label "x" to be the address of the next instruction to616** be inserted. The parameter "x" must have been obtained from617** a prior call to sqlite3VdbeMakeLabel().618*/619static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){620 int nNewSize = 10 - p->nLabel;621 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,622 nNewSize*sizeof(p->aLabel[0]));623 if( p->aLabel==0 ){624 p->nLabelAlloc = 0;625 }else{626#ifdef SQLITE_DEBUG627 int i;628 for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;629#endif630 if( nNewSize>=100 && (nNewSize/100)>(p->nLabelAlloc/100) ){631 sqlite3ProgressCheck(p);632 }633 p->nLabelAlloc = nNewSize;634 p->aLabel[j] = v->nOp;635 }636}637void sqlite3VdbeResolveLabel(Vdbe *v, int x){638 Parse *p = v->pParse;639 int j = ADDR(x);640 assert( v->eVdbeState==VDBE_INIT_STATE );641 assert( j<-p->nLabel );642 assert( j>=0 );643#ifdef SQLITE_DEBUG644 if( p->db->flags & SQLITE_VdbeAddopTrace ){645 printf("RESOLVE LABEL %d to %d\n", x, v->nOp);646 }647#endif648 if( p->nLabelAlloc + p->nLabel < 0 ){649 resizeResolveLabel(p,v,j);650 }else{651 assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */652 p->aLabel[j] = v->nOp;653 }654}655 656/*657** Mark the VDBE as one that can only be run one time.658*/659void sqlite3VdbeRunOnlyOnce(Vdbe *p){660 sqlite3VdbeAddOp2(p, OP_Expire, 1, 1);661}662 663/*664** Mark the VDBE as one that can be run multiple times.665*/666void sqlite3VdbeReusable(Vdbe *p){667 int i;668 for(i=1; ALWAYS(i<p->nOp); i++){669 if( ALWAYS(p->aOp[i].opcode==OP_Expire) ){670 p->aOp[1].opcode = OP_Noop;671 break;672 }673 }674}675 676#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */677 678/*679** The following type and function are used to iterate through all opcodes680** in a Vdbe main program and each of the sub-programs (triggers) it may681** invoke directly or indirectly. It should be used as follows:682**683** Op *pOp;684** VdbeOpIter sIter;685**686** memset(&sIter, 0, sizeof(sIter));687** sIter.v = v; // v is of type Vdbe*688** while( (pOp = opIterNext(&sIter)) ){689** // Do something with pOp690** }691** sqlite3DbFree(v->db, sIter.apSub);692**693*/694typedef struct VdbeOpIter VdbeOpIter;695struct VdbeOpIter {696 Vdbe *v; /* Vdbe to iterate through the opcodes of */697 SubProgram **apSub; /* Array of subprograms */698 int nSub; /* Number of entries in apSub */699 int iAddr; /* Address of next instruction to return */700 int iSub; /* 0 = main program, 1 = first sub-program etc. */701};702static Op *opIterNext(VdbeOpIter *p){703 Vdbe *v = p->v;704 Op *pRet = 0;705 Op *aOp;706 int nOp;707 708 if( p->iSub<=p->nSub ){709 710 if( p->iSub==0 ){711 aOp = v->aOp;712 nOp = v->nOp;713 }else{714 aOp = p->apSub[p->iSub-1]->aOp;715 nOp = p->apSub[p->iSub-1]->nOp;716 }717 assert( p->iAddr<nOp );718 719 pRet = &aOp[p->iAddr];720 p->iAddr++;721 if( p->iAddr==nOp ){722 p->iSub++;723 p->iAddr = 0;724 }725 726 if( pRet->p4type==P4_SUBPROGRAM ){727 i64 nByte = (1+(u64)p->nSub)*sizeof(SubProgram*);728 int j;729 for(j=0; j<p->nSub; j++){730 if( p->apSub[j]==pRet->p4.pProgram ) break;731 }732 if( j==p->nSub ){733 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);734 if( !p->apSub ){735 pRet = 0;736 }else{737 p->apSub[p->nSub++] = pRet->p4.pProgram;738 }739 }740 }741 }742 743 return pRet;744}745 746/*747** Check if the program stored in the VM associated with pParse may748** throw an ABORT exception (causing the statement, but not entire transaction749** to be rolled back). This condition is true if the main program or any750** sub-programs contains any of the following:751**752** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.753** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.754** * OP_Destroy755** * OP_VUpdate756** * OP_VCreate757** * OP_VRename758** * OP_FkCounter with P2==0 (immediate foreign key constraint)759** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine760** (for CREATE TABLE AS SELECT ...)761**762** Then check that the value of Parse.mayAbort is true if an763** ABORT may be thrown, or false otherwise. Return true if it does764** match, or false otherwise. This function is intended to be used as765** part of an assert statement in the compiler. Similar to:766**767** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );768*/769int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){770 int hasAbort = 0;771 int hasFkCounter = 0;772 int hasCreateTable = 0;773 int hasCreateIndex = 0;774 int hasInitCoroutine = 0;775 Op *pOp;776 VdbeOpIter sIter;777 778 if( v==0 ) return 0;779 memset(&sIter, 0, sizeof(sIter));780 sIter.v = v;781 782 while( (pOp = opIterNext(&sIter))!=0 ){783 int opcode = pOp->opcode;784 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename785 || opcode==OP_VDestroy786 || opcode==OP_VCreate787 || opcode==OP_ParseSchema788 || opcode==OP_Function || opcode==OP_PureFunc789 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)790 && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))791 ){792 hasAbort = 1;793 break;794 }795 if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;796 if( mayAbort ){797 /* hasCreateIndex may also be set for some DELETE statements that use798 ** OP_Clear. So this routine may end up returning true in the case799 ** where a "DELETE FROM tbl" has a statement-journal but does not800 ** require one. This is not so bad - it is an inefficiency, not a bug. */801 if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;802 if( opcode==OP_Clear ) hasCreateIndex = 1;803 }804 if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;805#ifndef SQLITE_OMIT_FOREIGN_KEY806 if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){807 hasFkCounter = 1;808 }809#endif810 }811 sqlite3DbFree(v->db, sIter.apSub);812 813 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.814 ** If malloc failed, then the while() loop above may not have iterated815 ** through all opcodes and hasAbort may be set incorrectly. Return816 ** true for this case to prevent the assert() in the callers frame817 ** from failing. */818 return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter819 || (hasCreateTable && hasInitCoroutine) || hasCreateIndex820 );821}822#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */823 824#ifdef SQLITE_DEBUG825/*826** Increment the nWrite counter in the VDBE if the cursor is not an827** ephemeral cursor, or if the cursor argument is NULL.828*/829void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){830 if( pC==0831 || (pC->eCurType!=CURTYPE_SORTER832 && pC->eCurType!=CURTYPE_PSEUDO833 && !pC->isEphemeral)834 ){835 p->nWrite++;836 }837}838#endif839 840#ifdef SQLITE_DEBUG841/*842** Assert if an Abort at this point in time might result in a corrupt843** database.844*/845void sqlite3VdbeAssertAbortable(Vdbe *p){846 assert( p->nWrite==0 || p->usesStmtJournal );847}848#endif849 850/*851** This routine is called after all opcodes have been inserted. It loops852** through all the opcodes and fixes up some details.853**854** (1) For each jump instruction with a negative P2 value (a label)855** resolve the P2 value to an actual address.856**857** (2) Compute the maximum number of arguments used by the xUpdate/xFilter858** methods of any virtual table and store that value in *pMaxVtabArgs.859**860** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately861** indicate what the prepared statement actually does.862**863** (4) (discontinued)864**865** (5) Reclaim the memory allocated for storing labels.866**867** This routine will only function correctly if the mkopcodeh.tcl generator868** script numbers the opcodes correctly. Changes to this routine must be869** coordinated with changes to mkopcodeh.tcl.870*/871static void resolveP2Values(Vdbe *p, int *pMaxVtabArgs){872 int nMaxVtabArgs = *pMaxVtabArgs;873 Op *pOp;874 Parse *pParse = p->pParse;875 int *aLabel = pParse->aLabel;876 877 assert( pParse->db->mallocFailed==0 ); /* tag-20230419-1 */878 p->readOnly = 1;879 p->bIsReader = 0;880 pOp = &p->aOp[p->nOp-1];881 assert( p->aOp[0].opcode==OP_Init );882 while( 1 /* Loop terminates when it reaches the OP_Init opcode */ ){883 /* Only JUMP opcodes and the short list of special opcodes in the switch884 ** below need to be considered. The mkopcodeh.tcl generator script groups885 ** all these opcodes together near the front of the opcode list. Skip886 ** any opcode that does not need processing by virtual of the fact that887 ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.888 */889 if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){890 /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing891 ** cases from this switch! */892 switch( pOp->opcode ){893 case OP_Transaction: {894 if( pOp->p2!=0 ) p->readOnly = 0;895 /* no break */ deliberate_fall_through896 }897 case OP_AutoCommit:898 case OP_Savepoint: {899 p->bIsReader = 1;900 break;901 }902#ifndef SQLITE_OMIT_WAL903 case OP_Checkpoint:904#endif905 case OP_Vacuum:906 case OP_JournalMode: {907 p->readOnly = 0;908 p->bIsReader = 1;909 break;910 }911 case OP_Init: {912 assert( pOp->p2>=0 );913 goto resolve_p2_values_loop_exit;914 }915#ifndef SQLITE_OMIT_VIRTUALTABLE916 case OP_VUpdate: {917 if( pOp->p2>nMaxVtabArgs ) nMaxVtabArgs = pOp->p2;918 break;919 }920 case OP_VFilter: {921 int n;922 /* The instruction immediately prior to VFilter will be an923 ** OP_Integer that sets the "argc" value for the VFilter. See924 ** the code where OP_VFilter is generated at tag-20250207a. */925 assert( (pOp - p->aOp) >= 3 );926 assert( pOp[-1].opcode==OP_Integer );927 assert( pOp[-1].p2==pOp->p3+1 );928 n = pOp[-1].p1;929 if( n>nMaxVtabArgs ) nMaxVtabArgs = n;930 /* Fall through into the default case */931 /* no break */ deliberate_fall_through932 }933#endif934 default: {935 if( pOp->p2<0 ){936 /* The mkopcodeh.tcl script has so arranged things that the only937 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to938 ** have non-negative values for P2. */939 assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );940 assert( ADDR(pOp->p2)<-pParse->nLabel );941 assert( aLabel!=0 ); /* True because of tag-20230419-1 */942 pOp->p2 = aLabel[ADDR(pOp->p2)];943 }944 945 /* OPFLG_JUMP opcodes never have P2==0, though OPFLG_JUMP0 opcodes946 ** might */947 assert( pOp->p2>0 948 || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP0)!=0 );949 950 /* Jumps never go off the end of the bytecode array */951 assert( pOp->p2<p->nOp952 || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)==0 );953 break;954 }955 }956 /* The mkopcodeh.tcl script has so arranged things that the only957 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to958 ** have non-negative values for P2. */959 assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);960 }961 assert( pOp>p->aOp ); 962 pOp--;963 }964resolve_p2_values_loop_exit:965 if( aLabel ){966 sqlite3DbNNFreeNN(p->db, pParse->aLabel);967 pParse->aLabel = 0;968 }969 pParse->nLabel = 0;970 *pMaxVtabArgs = nMaxVtabArgs;971 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );972}973 974#ifdef SQLITE_DEBUG975/*976** Check to see if a subroutine contains a jump to a location outside of977** the subroutine. If a jump outside the subroutine is detected, add code978** that will cause the program to halt with an error message.979**980** The subroutine consists of opcodes between iFirst and iLast. Jumps to981** locations within the subroutine are acceptable. iRetReg is a register982** that contains the return address. Jumps to outside the range of iFirst983** through iLast are also acceptable as long as the jump destination is984** an OP_Return to iReturnAddr.985**986** A jump to an unresolved label means that the jump destination will be987** beyond the current address. That is normally a jump to an early988** termination and is consider acceptable.989**990** This routine only runs during debug builds. The purpose is (of course)991** to detect invalid escapes out of a subroutine. The OP_Halt opcode992** is generated rather than an assert() or other error, so that ".eqp full"993** will still work to show the original bytecode, to aid in debugging.994*/995void sqlite3VdbeNoJumpsOutsideSubrtn(996 Vdbe *v, /* The byte-code program under construction */997 int iFirst, /* First opcode of the subroutine */998 int iLast, /* Last opcode of the subroutine */999 int iRetReg /* Subroutine return address register */1000){1001 VdbeOp *pOp;1002 Parse *pParse;1003 int i;1004 sqlite3_str *pErr = 0;1005 assert( v!=0 );1006 pParse = v->pParse;1007 assert( pParse!=0 );1008 if( pParse->nErr ) return;1009 assert( iLast>=iFirst );1010 assert( iLast<v->nOp );1011 pOp = &v->aOp[iFirst];1012 for(i=iFirst; i<=iLast; i++, pOp++){1013 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ){1014 int iDest = pOp->p2; /* Jump destination */1015 if( iDest==0 ) continue;1016 if( pOp->opcode==OP_Gosub ) continue;1017 if( pOp->p3==20230325 && pOp->opcode==OP_NotNull ){1018 /* This is a deliberately taken illegal branch. tag-20230325-2 */1019 continue;1020 }1021 if( iDest<0 ){1022 int j = ADDR(iDest);1023 assert( j>=0 );1024 if( j>=-pParse->nLabel || pParse->aLabel[j]<0 ){1025 continue;1026 }1027 iDest = pParse->aLabel[j];1028 }1029 if( iDest<iFirst || iDest>iLast ){1030 int j = iDest;1031 for(; j<v->nOp; j++){1032 VdbeOp *pX = &v->aOp[j];1033 if( pX->opcode==OP_Return ){1034 if( pX->p1==iRetReg ) break;1035 continue;1036 }1037 if( pX->opcode==OP_Noop ) continue;1038 if( pX->opcode==OP_Explain ) continue;1039 if( pErr==0 ){1040 pErr = sqlite3_str_new(0);1041 }else{1042 sqlite3_str_appendchar(pErr, 1, '\n');1043 }1044 sqlite3_str_appendf(pErr,1045 "Opcode at %d jumps to %d which is outside the "1046 "subroutine at %d..%d",1047 i, iDest, iFirst, iLast);1048 break;1049 }1050 }1051 }1052 }1053 if( pErr ){1054 char *zErr = sqlite3_str_finish(pErr);1055 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_INTERNAL, OE_Abort, 0, zErr, 0);1056 sqlite3_free(zErr);1057 sqlite3MayAbort(pParse);1058 }1059}1060#endif /* SQLITE_DEBUG */1061 1062/*1063** Return the address of the next instruction to be inserted.1064*/1065int sqlite3VdbeCurrentAddr(Vdbe *p){1066 assert( p->eVdbeState==VDBE_INIT_STATE );1067 return p->nOp;1068}1069 1070/*1071** Verify that at least N opcode slots are available in p without1072** having to malloc for more space (except when compiled using1073** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing1074** to verify that certain calls to sqlite3VdbeAddOpList() can never1075** fail due to a OOM fault and hence that the return value from1076** sqlite3VdbeAddOpList() will always be non-NULL.1077*/1078#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)1079void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){1080 assert( p->nOp + N <= p->nOpAlloc );1081}1082#endif1083 1084/*1085** Verify that the VM passed as the only argument does not contain1086** an OP_ResultRow opcode. Fail an assert() if it does. This is used1087** by code in pragma.c to ensure that the implementation of certain1088** pragmas comports with the flags specified in the mkpragmatab.tcl1089** script.1090*/1091#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)1092void sqlite3VdbeVerifyNoResultRow(Vdbe *p){1093 int i;1094 for(i=0; i<p->nOp; i++){1095 assert( p->aOp[i].opcode!=OP_ResultRow );1096 }1097}1098#endif1099 1100/*1101** Generate code (a single OP_Abortable opcode) that will1102** verify that the VDBE program can safely call Abort in the current1103** context.1104*/1105#if defined(SQLITE_DEBUG)1106void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){1107 if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);1108}1109#endif1110 1111/*1112** This function returns a pointer to the array of opcodes associated with1113** the Vdbe passed as the first argument. It is the callers responsibility1114** to arrange for the returned array to be eventually freed using the1115** vdbeFreeOpArray() function.1116**1117** Before returning, *pnOp is set to the number of entries in the returned1118** array. Also, *pnMaxArg is set to the larger of its current value and1119** the number of entries in the Vdbe.apArg[] array required to execute the1120** returned program.1121*/1122VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){1123 VdbeOp *aOp = p->aOp;1124 assert( aOp && !p->db->mallocFailed );1125 1126 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */1127 assert( DbMaskAllZero(p->btreeMask) );1128 1129 resolveP2Values(p, pnMaxArg);1130 *pnOp = p->nOp;1131 p->aOp = 0;1132 return aOp;1133}1134 1135/*1136** Add a whole list of operations to the operation stack. Return a1137** pointer to the first operation inserted.1138**1139** Non-zero P2 arguments to jump instructions are automatically adjusted1140** so that the jump target is relative to the first operation inserted.1141*/1142VdbeOp *sqlite3VdbeAddOpList(1143 Vdbe *p, /* Add opcodes to the prepared statement */1144 int nOp, /* Number of opcodes to add */1145 VdbeOpList const *aOp, /* The opcodes to be added */1146 int iLineno /* Source-file line number of first opcode */1147){1148 int i;1149 VdbeOp *pOut, *pFirst;1150 assert( nOp>0 );1151 assert( p->eVdbeState==VDBE_INIT_STATE );1152 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){1153 return 0;1154 }1155 pFirst = pOut = &p->aOp[p->nOp];1156 for(i=0; i<nOp; i++, aOp++, pOut++){1157 pOut->opcode = aOp->opcode;1158 pOut->p1 = aOp->p1;1159 pOut->p2 = aOp->p2;1160 assert( aOp->p2>=0 );1161 if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){1162 pOut->p2 += p->nOp;1163 }1164 pOut->p3 = aOp->p3;1165 pOut->p4type = P4_NOTUSED;1166 pOut->p4.p = 0;1167 pOut->p5 = 0;1168#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS1169 pOut->zComment = 0;1170#endif1171#ifdef SQLITE_VDBE_COVERAGE1172 pOut->iSrcLine = iLineno+i;1173#else1174 (void)iLineno;1175#endif1176#ifdef SQLITE_DEBUG1177 if( p->db->flags & SQLITE_VdbeAddopTrace ){1178 sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);1179 }1180#endif1181 }1182 p->nOp += nOp;1183 return pFirst;1184}1185 1186#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)1187/*1188** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().1189*/1190void sqlite3VdbeScanStatus(1191 Vdbe *p, /* VM to add scanstatus() to */1192 int addrExplain, /* Address of OP_Explain (or 0) */1193 int addrLoop, /* Address of loop counter */1194 int addrVisit, /* Address of rows visited counter */1195 LogEst nEst, /* Estimated number of output rows */1196 const char *zName /* Name of table or index being scanned */1197){1198 if( IS_STMT_SCANSTATUS(p->db) ){1199 i64 nByte = (1+(i64)p->nScan) * sizeof(ScanStatus);1200 ScanStatus *aNew;