interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / vdbeaux.c

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