./src/main.c

1010 return sqlite3ApiExit(0, rc);
1011}
1012#endif /* SQLITE_OMIT_UTF16 */
1013
1014/*
1015** The following routine destroys a virtual machine that is created by
1016** the sqlite3_compile() routine. The integer returned is an SQLITE_
1017** success/failure code that describes the result of executing the virtual
1018** machine.
1019**
1020** This routine sets the error code and string returned by
1021** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
1022*/
1023int sqlite3_finalize(sqlite3_stmt *pStmt){
1024 int rc;
1025 if( pStmt==0 ){
1026 rc = SQLITE_OK;
1027 }else{
1028 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
1029 }
1030 return rc;
1031}
1032
1033/*
1034** Terminate the current execution of an SQL statement and reset it
1035** back to its starting state so that it can be reused. A success code from
1036** the prior execution is returned.
1037**
1038** This routine sets the error code and string returned by
1039** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
1040*/
1041int sqlite3_reset(sqlite3_stmt *pStmt){
1042 int rc;
1043 if( pStmt==0 ){
1044 rc = SQLITE_OK;
1045 }else{

./src/os_common.h

159 if( p2 ){
160 *(int *)p2 = n;
161 p2 += 8;
162 }
163 return (void *)p2;
164}
165void sqlite3GenericFree(void *p){
166 assert(p);
167 free((void *)((char *)p - 8));
168}
169int sqlite3GenericAllocationSize(void *p){
170 return p ? *(int *)((char *)p - 8) : 0;
171}
172#else
173void *sqlite3GenericMalloc(int n){
174 char *p = (char *)malloc(n);
175 return (void *)p;
176}
177void *sqlite3GenericRealloc(void *p, int n){
178 assert(n>0);
179 p = realloc(p, n);
180 return p;
181}
182void sqlite3GenericFree(void *p){
183 assert(p);
184 free(p);
185}
186/* Never actually used, but needed for the linker */
187int sqlite3GenericAllocationSize(void *p){ return 0; }
188#endif

./src/vdbeapi.c

153/*
154** Execute the statement pStmt, either until a row of data is ready, the
155** statement is completely executed or an error occurs.
156**
157** This routine implements the bulk of the logic behind the sqlite_step()
158** API. The only thing omitted is the automatic recompile if a
159** schema change has occurred. That detail is handled by the
160** outer sqlite3_step() wrapper procedure.
161*/
162static int sqlite3Step(Vdbe *p){
163 sqlite3 *db;
164 int rc;
165
166 /* Assert that malloc() has not failed */
167 assert( !sqlite3MallocFailed() );
168
169 if( p==0 || p->magic!=VDBE_MAGIC_RUN ){
170 return SQLITE_MISUSE;
171 }
172 if( p->aborted ){
173 return SQLITE_ABORT;
174 }
175 if( p->pc<=0 && p->expired ){
176 if( p->rc==SQLITE_OK ){
177 p->rc = SQLITE_SCHEMA;
178 }
179 rc = SQLITE_ERROR;
180 goto end_of_step;
181 }
182 db = p->db;
183 if( sqlite3SafetyOn(db) ){
184 p->rc = SQLITE_MISUSE;
185 return SQLITE_MISUSE;
186 }
187 if( p->pc<0 ){
188 /* If there are no other statements currently running, then
189 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
190 ** from interrupting a statement that has not yet started.
191 */
192 if( db->activeVdbeCnt==0 ){
193 db->u1.isInterrupted = 0;
194 }
195
196#ifndef SQLITE_OMIT_TRACE
197 /* Invoke the trace callback if there is one
198 */
199 if( db->xTrace && !db->init.busy ){
200 assert( p->nOp>0 );
201 assert( p->aOp[p->nOp-1].opcode==OP_Noop );
202 assert( p->aOp[p->nOp-1].p3!=0 );
203 assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
204 sqlite3SafetyOff(db);
205 db->xTrace(db->pTraceArg, p->aOp[p->nOp-1].p3);
206 if( sqlite3SafetyOn(db) ){
207 p->rc = SQLITE_MISUSE;
208 return SQLITE_MISUSE;
209 }
210 }
211 if( db->xProfile && !db->init.busy ){
212 double rNow;
213 sqlite3OsCurrentTime(&rNow);
214 p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
215 }
216#endif
217
218 /* Print a copy of SQL as it is executed if the SQL_TRACE pragma is turned
219 ** on in debugging mode.
220 */
221#ifdef SQLITE_DEBUG
222 if( (db->flags & SQLITE_SqlTrace)!=0 ){
223 sqlite3DebugPrintf("SQL-trace: %s\n", p->aOp[p->nOp-1].p3);
224 }
225#endif /* SQLITE_DEBUG */
226
227 db->activeVdbeCnt++;
228 p->pc = 0;
229 }
230#ifndef SQLITE_OMIT_EXPLAIN
231 if( p->explain ){
232 rc = sqlite3VdbeList(p);
233 }else
234#endif /* SQLITE_OMIT_EXPLAIN */
235 {
236 rc = sqlite3VdbeExec(p);
237 }
238
239 if( sqlite3SafetyOff(db) ){
240 rc = SQLITE_MISUSE;
241 }
242
243#ifndef SQLITE_OMIT_TRACE
244 /* Invoke the profile callback if there is one
245 */
246 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy ){
247 double rNow;
248 u64 elapseTime;
249
250 sqlite3OsCurrentTime(&rNow);
251 elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
252 assert( p->nOp>0 );
253 assert( p->aOp[p->nOp-1].opcode==OP_Noop );
254 assert( p->aOp[p->nOp-1].p3!=0 );
255 assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC );
256 db->xProfile(db->pProfileArg, p->aOp[p->nOp-1].p3, elapseTime);
257 }
258#endif
259
260 sqlite3Error(p->db, rc, 0);
261 p->rc = sqlite3ApiExit(p->db, p->rc);
262end_of_step:
263 assert( (rc&0xff)==rc );
264 if( p->zSql && (rc&0xff)<SQLITE_ROW ){
265 /* This behavior occurs if sqlite3_prepare_v2() was used to build
266 ** the prepared statement. Return error codes directly */
267 return p->rc;
268 }else{
269 /* This is for legacy sqlite3_prepare() builds and when the code
270 ** is SQLITE_ROW or SQLITE_DONE */
271 return rc;
272 }
273}
274
275/*
276** This is the top-level implementation of sqlite3_step(). Call
277** sqlite3Step() to do most of the work. If a schema error occurs,
278** call sqlite3Reprepare() and try again.
279*/
280#ifdef SQLITE_OMIT_PARSER
281int sqlite3_step(sqlite3_stmt *pStmt){
282 return sqlite3Step((Vdbe*)pStmt);
283}
284#else
285int sqlite3_step(sqlite3_stmt *pStmt){
286 int cnt = 0;
287 int rc;
288 Vdbe *v = (Vdbe*)pStmt;
289 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
290 && cnt++ < 5
291 && sqlite3Reprepare(v) ){
292 sqlite3_reset(pStmt);
293 v->expired = 0;
294 }
295 return rc;
296}
297#endif
298
299/*
300** Extract the user data from a sqlite3_context structure and return a
301** pointer to it.
302*/
303void *sqlite3_user_data(sqlite3_context *p){
304 assert( p && p->pFunc );
305 return p->pFunc->pUserData;
306}
307
308/*
309** The following is the implementation of an SQL function that always
310** fails with an error message stating that the function is used in the

./src/util.c

574 sqlite3ReleaseThreadData();
575 }
576 }
577}
578#else
579#define updateMemoryUsedCount(x) /* no-op */
580#endif
581
582/*
583** Allocate and return N bytes of uninitialised memory by calling
584** sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory
585** by calling sqlite3_release_memory().
586*/
587void *sqlite3MallocRaw(int n, int doMemManage){
588 void *p = 0;
589 if( n>0 && !sqlite3MallocFailed() && (!doMemManage || enforceSoftLimit(n)) ){
590 while( (p = OSMALLOC(n))==0 && sqlite3_release_memory(n) ){}
591 if( !p ){
592 sqlite3FailedMalloc();
593 OSMALLOC_FAILED();
594 }else if( doMemManage ){
595 updateMemoryUsedCount(OSSIZEOF(p));
596 }
597 }
598 return p;
599}
600
601/*
602** Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The
603** pointer to the new allocation is returned. If the Realloc() call fails,
604** attempt to free memory by calling sqlite3_release_memory().
605*/
606void *sqlite3Realloc(void *p, int n){
607 if( sqlite3MallocFailed() ){
608 return 0;
609 }
610
611 if( !p ){
612 return sqlite3Malloc(n, 1);
613 }else{

621 sqlite3FailedMalloc();
622 OSMALLOC_FAILED();
623 }else{
624 updateMemoryUsedCount(OSSIZEOF(np) - origSize);
625 }
626 }
627 return np;
628 }
629}
630
631/*
632** Free the memory pointed to by p. p must be either a NULL pointer or a
633** value returned by a previous call to sqlite3Malloc() or sqlite3Realloc().
634*/
635void sqlite3FreeX(void *p){
636 if( p ){
637 updateMemoryUsedCount(0 - OSSIZEOF(p));
638 OSFREE(p);
639 }
640}
641
642/*
643** A version of sqliteMalloc() that is always a function, not a macro.
644** Currently, this is used only to alloc to allocate the parser engine.
645*/
646void *sqlite3MallocX(int n){
647 return sqliteMalloc(n);
648}
649
650/*
651** sqlite3Malloc
652** sqlite3ReallocOrFree
653**
654** These two are implemented as wrappers around sqlite3MallocRaw(),

732 zNew = sqlite3MallocRaw(n+1, 1);
733 if( zNew ){
734 memcpy(zNew, z, n);
735 zNew[n] = 0;
736 }
737 return zNew;
738}
739
740/*
741** Create a string from the 2nd and subsequent arguments (up to the
742** first NULL argument), store the string in memory obtained from
743** sqliteMalloc() and make the pointer indicated by the 1st argument
744** point to that string. The 1st argument must either be NULL or
745** point to memory obtained from sqliteMalloc().
746*/
747void sqlite3SetString(char **pz, ...){
748 va_list ap;
749 int nByte;
750 const char *z;
751 char *zResult;
752
753 if( pz==0 ) return;
754 nByte = 1;
755 va_start(ap, pz);
756 while( (z = va_arg(ap, const char*))!=0 ){
757 nByte += strlen(z);
758 }
759 va_end(ap);
760 sqliteFree(*pz);
761 *pz = zResult = sqliteMallocRaw( nByte );
762 if( zResult==0 ){
763 return;
764 }
765 *zResult = 0;
766 va_start(ap, pz);
767 while( (z = va_arg(ap, const char*))!=0 ){
768 strcpy(zResult, z);
769 zResult += strlen(zResult);
770 }
771 va_end(ap);
772}
773
774/*
775** Set the most recent error code and error string for the sqlite
776** handle "db". The error code is set to "err_code".
777**
778** If it is not NULL, string zFormat specifies the format of the
779** error string in the style of the printf functions: The following
780** format characters are allowed:
781**
782** %s Insert a string
783** %z A string that should be freed after use
784** %d Insert an integer
785** %T Insert a token
786** %S Insert the first element of a SrcList
787**
788** zFormat and any string tokens that follow it are assumed to be
789** encoded in UTF-8.
790**
791** To clear the most recent error for sqlite handle "db", sqlite3Error
792** should be called with err_code set to SQLITE_OK and zFormat set
793** to NULL.
794*/
795void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
796 if( db && (db->pErr || (db->pErr = sqlite3ValueNew())!=0) ){
797 db->errCode = err_code;
798 if( zFormat ){
799 char *z;
800 va_list ap;
801 va_start(ap, zFormat);
802 z = sqlite3VMPrintf(zFormat, ap);
803 va_end(ap);
804 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3FreeX);
805 }else{
806 sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
807 }
808 }
809}
810
811/*
812** Add an error message to pParse->zErrMsg and increment pParse->nErr.
813** The following formatting characters are allowed:
814**
815** %s Insert a string
816** %z A string that should be freed after use
817** %d Insert an integer
818** %T Insert a token
819** %S Insert the first element of a SrcList
820**
821** This function should be used to report any error that occurs whilst
822** compiling an SQL statement (i.e. within sqlite3_prepare()). The
823** last thing the sqlite3_prepare() function does is copy the error

1133** when this routine is called.
1134**
1135** This routine is a attempt to detect if two threads use the
1136** same sqlite* pointer at the same time. There is a race
1137** condition so it is possible that the error is not detected.
1138** But usually the problem will be seen. The result will be an
1139** error which can be used to debug the application that is
1140** using SQLite incorrectly.
1141**
1142** Ticket #202: If db->magic is not a valid open value, take care not
1143** to modify the db structure at all. It could be that db is a stale
1144** pointer. In other words, it could be that there has been a prior
1145** call to sqlite3_close(db) and db has been deallocated. And we do
1146** not want to write into deallocated memory.
1147*/
1148int sqlite3SafetyOn(sqlite3 *db){
1149 if( db->magic==SQLITE_MAGIC_OPEN ){
1150 db->magic = SQLITE_MAGIC_BUSY;
1151 return 0;
1152 }else if( db->magic==SQLITE_MAGIC_BUSY ){
1153 db->magic = SQLITE_MAGIC_ERROR;
1154 db->u1.isInterrupted = 1;
1155 }
1156 return 1;
1157}
1158
1159/*
1160** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
1161** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
1162** when this routine is called.
1163*/
1164int sqlite3SafetyOff(sqlite3 *db){
1165 if( db->magic==SQLITE_MAGIC_BUSY ){
1166 db->magic = SQLITE_MAGIC_OPEN;
1167 return 0;
1168 }else if( db->magic==SQLITE_MAGIC_OPEN ){
1169 db->magic = SQLITE_MAGIC_ERROR;
1170 db->u1.isInterrupted = 1;
1171 }
1172 return 1;
1173}
1174
1175/*
1176** Check to make sure we have a valid db pointer. This test is not
1177** foolproof but it does provide some measure of protection against
1178** misuse of the interface such as passing in db pointers that are
1179** NULL or which have been previously closed. If this routine returns
1180** TRUE it means that the db pointer is invalid and should not be
1181** dereferenced for any reason. The calling function should invoke
1182** SQLITE_MISUSE immediately.
1183*/
1184int sqlite3SafetyCheck(sqlite3 *db){
1185 int magic;
1186 if( db==0 ) return 1;
1187 magic = db->magic;

1428/*
1429** This function must be called before exiting any API function (i.e.
1430** returning control to the user) that has called sqlite3Malloc or
1431** sqlite3Realloc.
1432**
1433** The returned value is normally a copy of the second argument to this
1434** function. However, if a malloc() failure has occured since the previous
1435** invocation SQLITE_NOMEM is returned instead.
1436**
1437** If the first argument, db, is not NULL and a malloc() error has occured,
1438** then the connection error-code (the value returned by sqlite3_errcode())
1439** is set to SQLITE_NOMEM.
1440*/
1441static int mallocHasFailed = 0;
1442int sqlite3ApiExit(sqlite3* db, int rc){
1443 if( sqlite3MallocFailed() ){
1444 mallocHasFailed = 0;
1445 sqlite3OsLeaveMutex();
1446 sqlite3Error(db, SQLITE_NOMEM, 0);
1447 rc = SQLITE_NOMEM;
1448 }
1449 return rc & (db ? db->errMask : 0xff);
1450}
1451
1452/*
1453** Return true is a malloc has failed in this thread since the last call
1454** to sqlite3ApiExit(), or false otherwise.
1455*/
1456int sqlite3MallocFailed(){
1457 return (mallocHasFailed && sqlite3OsInMutex(1));
1458}
1459
1460/*
1461** Set the "malloc has failed" condition to true for this thread.
1462*/
1463void sqlite3FailedMalloc(){
1464 sqlite3OsEnterMutex();
1465 assert( mallocHasFailed==0 );
1466 mallocHasFailed = 1;
1467}
1468
1469#ifdef SQLITE_MEMDEBUG
1470/*
1471** This function sets a flag in the thread-specific-data structure that will
1472** cause an assert to fail if sqliteMalloc() or sqliteRealloc() is called.

./src/btree.c

2588 }else{
2589 rc = SQLITE_OK;
2590 }
2591 pBt->inStmt = 0;
2592 return rc;
2593}
2594
2595/*
2596** Rollback the active statement subtransaction. If no subtransaction
2597** is active this routine is a no-op.
2598**
2599** All cursors will be invalidated by this operation. Any attempt
2600** to use a cursor that was open at the beginning of this operation
2601** will result in an error.
2602*/
2603int sqlite3BtreeRollbackStmt(Btree *p){
2604 int rc = SQLITE_OK;
2605 BtShared *pBt = p->pBt;
2606 sqlite3MallocDisallow();
2607 if( pBt->inStmt && !pBt->readOnly ){
2608 rc = sqlite3pager_stmt_rollback(pBt->pPager);
2609 assert( countWriteCursors(pBt)==0 );
2610 pBt->inStmt = 0;
2611 }
2612 sqlite3MallocAllow();
2613 return rc;
2614}
2615
2616/*
2617** Default key comparison function to be used if no comparison function
2618** is specified on the sqlite3BtreeCursor() call.
2619*/
2620static int dfltCompare(
2621 void *NotUsed, /* User data is not used */
2622 int n1, const void *p1, /* First key to compare */
2623 int n2, const void *p2 /* Second key to compare */
2624){
2625 int c;
2626 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2627 if( c==0 ){
2628 c = n1 - n2;

./src/vdbe.c

406**
407** If the callback ever returns non-zero, then the program exits
408** immediately. There will be no error message but the p->rc field is
409** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
410**
411** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
412** routine to return SQLITE_ERROR.
413**
414** Other fatal errors return SQLITE_ERROR.
415**
416** After this routine has finished, sqlite3VdbeFinalize() should be
417** used to clean up the mess that was left behind.
418*/
419int sqlite3VdbeExec(
420 Vdbe *p /* The VDBE */
421){
422 int pc; /* The program counter */
423 Op *pOp; /* Current operation */
424 int rc = SQLITE_OK; /* Value to return */
425 sqlite3 *db = p->db; /* The database */
426 u8 encoding = ENC(db); /* The database encoding */
427 Mem *pTos; /* Top entry in the operand stack */
428#ifdef VDBE_PROFILE
429 unsigned long long start; /* CPU clock count at start of opcode */
430 int origPc; /* Program counter at start of opcode */
431#endif
432#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
433 int nProgressOps = 0; /* Opcodes executed since progress callback. */
434#endif
435#ifndef NDEBUG
436 Mem *pStackLimit;
437#endif
438
439 if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
440 assert( db->magic==SQLITE_MAGIC_BUSY );
441 pTos = p->pTos;
442 if( p->rc==SQLITE_NOMEM ){
443 /* This happens if a malloc() inside a call to sqlite3_column_text() or
444 ** sqlite3_column_text16() failed. */
445 goto no_mem;
446 }
447 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
448 p->rc = SQLITE_OK;
449 assert( p->explain==0 );
450 if( p->popStack ){
451 popStack(&pTos, p->popStack);
452 p->popStack = 0;
453 }
454 p->resOnStack = 0;
455 db->busyHandler.nBusy = 0;
456 CHECK_FOR_INTERRUPT;
457#ifdef SQLITE_DEBUG
458 if( (p->db->flags & SQLITE_VdbeListing)!=0
459 || sqlite3OsFileExists("vdbe_explain")
460 ){
461 int i;
462 printf("VDBE Program Listing:\n");
463 sqlite3VdbePrintSql(p);
464 for(i=0; i<p->nOp; i++){
465 sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
466 }
467 }
468 if( sqlite3OsFileExists("vdbe_trace") ){
469 p->trace = stdout;
470 }
471#endif
472 for(pc=p->pc; rc==SQLITE_OK; pc++){
473 assert( pc>=0 && pc<p->nOp );
474 assert( pTos<=&p->aStack[pc] );
475 if( sqlite3MallocFailed() ) goto no_mem;
476#ifdef VDBE_PROFILE
477 origPc = pc;
478 start = hwtime();
479#endif
480 pOp = &p->aOp[pc];
481
482 /* Only allow tracing if SQLITE_DEBUG is defined.
483 */
484#ifdef SQLITE_DEBUG
485 if( p->trace ){
486 if( pc==0 ){
487 printf("VDBE Execution Trace:\n");
488 sqlite3VdbePrintSql(p);
489 }
490 sqlite3VdbePrintOp(p->trace, pc, pOp);
491 }
492 if( p->trace==0 && pc==0 && sqlite3OsFileExists("vdbe_sqltrace") ){
493 sqlite3VdbePrintSql(p);
494 }
495#endif
496
497
498 /* Check to see if we need to simulate an interrupt. This only happens
499 ** if we have a special test build.
500 */
501#ifdef SQLITE_TEST
502 if( sqlite3_interrupt_count>0 ){
503 sqlite3_interrupt_count--;
504 if( sqlite3_interrupt_count==0 ){
505 sqlite3_interrupt(db);
506 }
507 }
508#endif
509
510#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
511 /* Call the progress callback if it is configured and the required number
512 ** of VDBE ops have been executed (either since this invocation of
513 ** sqlite3VdbeExec() or since last time the progress callback was called).
514 ** If the progress callback returns non-zero, exit the virtual machine with
515 ** a return code SQLITE_ABORT.
516 */
517 if( db->xProgress ){
518 if( db->nProgressOps==nProgressOps ){
519 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
520 if( db->xProgress(db->pProgressArg)!=0 ){
521 sqlite3SafetyOn(db);
522 rc = SQLITE_ABORT;
523 continue; /* skip to the next iteration of the for loop */
524 }
525 nProgressOps = 0;
526 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
527 }
528 nProgressOps++;
529 }
530#endif
531
532#ifndef NDEBUG
533 /* This is to check that the return value of static function
534 ** opcodeNoPush() (see vdbeaux.c) returns values that match the
535 ** implementation of the virtual machine in this file. If
536 ** opcodeNoPush() returns non-zero, then the stack is guarenteed
537 ** not to grow when the opcode is executed. If it returns zero, then
538 ** the stack may grow by at most 1.
539 **
540 ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not
541 ** available if NDEBUG is defined at build time.
542 */
543 pStackLimit = pTos;
544 if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){
545 pStackLimit++;
546 }
547#endif
548
549 switch( pOp->opcode ){
550
551/*****************************************************************************
552** What follows is a massive switch statement where each case implements a
553** separate instruction in the virtual machine. If we follow the usual
554** indentation conventions, each case should be indented by 6 spaces. But
555** that is a lot of wasted space on the left margin. So the code within
556** the switch statement will break with convention and be flush-left. Another
557** big comment (similar to this one) will mark the point in the code where
558** we transition back to normal indentation.
559**
560** The formatting of each case is important. The makefile for SQLite
561** generates two C files "opcodes.h" and "opcodes.c" by scanning this
562** file looking for lines that begin with "case OP_". The opcodes.h files
563** will be filled with #defines that give unique integer values to each

2322 rc = sqlite3BtreeBeginStmt(pBt);
2323 }
2324 }
2325 break;
2326}
2327
2328/* Opcode: AutoCommit P1 P2 *
2329**
2330** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
2331** back any currently active btree transactions. If there are any active
2332** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
2333**
2334** This instruction causes the VM to halt.
2335*/
2336case OP_AutoCommit: { /* no-push */
2337 u8 i = pOp->p1;
2338 u8 rollback = pOp->p2;
2339
2340 assert( i==1 || i==0 );
2341 assert( i==1 || rollback==0 );
2342
2343 assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
2344
2345 if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
2346 /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
2347 ** still running, and a transaction is active, return an error indicating
2348 ** that the other VMs must complete first.
2349 */
2350 sqlite3SetString(&p->zErrMsg, "cannot ", rollback?"rollback":"commit",
2351 " transaction - SQL statements in progress", (char*)0);
2352 rc = SQLITE_ERROR;
2353 }else if( i!=db->autoCommit ){
2354 if( pOp->p2 ){
2355 assert( i==1 );
2356 sqlite3RollbackAll(db);
2357 db->autoCommit = 1;
2358 }else{
2359 db->autoCommit = i;
2360 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
2361 p->pTos = pTos;
2362 p->pc = pc;
2363 db->autoCommit = 1-i;
2364 p->rc = SQLITE_BUSY;

4884*/
4885default: {
4886 assert( 0 );
4887 break;
4888}
4889
4890/*****************************************************************************
4891** The cases of the switch statement above this line should all be indented
4892** by 6 spaces. But the left-most 6 spaces have been removed to improve the
4893** readability. From this point on down, the normal indentation rules are
4894** restored.
4895*****************************************************************************/
4896 }
4897
4898 /* Make sure the stack limit was not exceeded */
4899 assert( pTos<=pStackLimit );
4900
4901#ifdef VDBE_PROFILE
4902 {
4903 long long elapse = hwtime() - start;
4904 pOp->cycles += elapse;
4905 pOp->cnt++;
4906#if 0
4907 fprintf(stdout, "%10lld ", elapse);
4908 sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
4909#endif
4910 }
4911#endif
4912
4913 /* The following code adds nothing to the actual functionality
4914 ** of the program. It is only here for testing and debugging.
4915 ** On the other hand, it does burn CPU cycles every time through
4916 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
4917 */
4918#ifndef NDEBUG
4919 /* Sanity checking on the top element of the stack. If the previous
4920 ** instruction was VNoChange, then the flags field of the top
4921 ** of the stack is set to 0. This is technically invalid for a memory
4922 ** cell, so avoid calling MemSanity() in this case.
4923 */
4924 if( pTos>=p->aStack && pTos->flags ){
4925 sqlite3VdbeMemSanity(pTos);
4926 }
4927 assert( pc>=-1 && pc<p->nOp );
4928#ifdef SQLITE_DEBUG
4929 /* Code for tracing the vdbe stack. */
4930 if( p->trace && pTos>=p->aStack ){
4931 int i;
4932 fprintf(p->trace, "Stack:");
4933 for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
4934 if( pTos[i].flags & MEM_Null ){
4935 fprintf(p->trace, " NULL");
4936 }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
4937 fprintf(p->trace, " si:%lld", pTos[i].i);
4938 }else if( pTos[i].flags & MEM_Int ){
4939 fprintf(p->trace, " i:%lld", pTos[i].i);
4940 }else if( pTos[i].flags & MEM_Real ){
4941 fprintf(p->trace, " r:%g", pTos[i].r);
4942 }else{
4943 char zBuf[100];
4944 sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf);
4945 fprintf(p->trace, " ");
4946 fprintf(p->trace, "%s", zBuf);
4947 }
4948 }
4949 if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
4950 fprintf(p->trace,"\n");
4951 }
4952#endif /* SQLITE_DEBUG */
4953#endif /* NDEBUG */
4954 } /* The end of the for(;;) loop the loops through opcodes */
4955
4956 /* If we reach this point, it means that execution is finished.
4957 */
4958vdbe_halt:
4959 if( rc ){
4960 p->rc = rc;
4961 rc = SQLITE_ERROR;
4962 }else{
4963 rc = SQLITE_DONE;
4964 }
4965 sqlite3VdbeHalt(p);
4966 p->pTos = pTos;
4967 return rc;
4968
4969 /* Jump to here if a malloc() fails. It's hard to get a malloc()
4970 ** to fail on a modern VM computer, so this code is untested.
4971 */
4972no_mem:
4973 sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0);
4974 rc = SQLITE_NOMEM;
4975 goto vdbe_halt;
4976
4977 /* Jump to here for an SQLITE_MISUSE error.
4978 */
4979abort_due_to_misuse:
4980 rc = SQLITE_MISUSE;

4990 }
4991 goto vdbe_halt;
4992
4993 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
4994 ** flag.
4995 */
4996abort_due_to_interrupt:
4997 assert( db->u1.isInterrupted );
4998 if( db->magic!=SQLITE_MAGIC_BUSY ){
4999 rc = SQLITE_MISUSE;
5000 }else{
5001 rc = SQLITE_INTERRUPT;
5002 }
5003 p->rc = rc;
5004 sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0);
5005 goto vdbe_halt;
5006}

./src/vdbeaux.c

210** a prior call to sqlite3VdbeMakeLabel().
211*/
212void sqlite3VdbeResolveLabel(Vdbe *p, int x){
213 int j = -1-x;
214 assert( p->magic==VDBE_MAGIC_INIT );
215 assert( j>=0 && j<p->nLabel );
216 if( p->aLabel ){
217 p->aLabel[j] = p->nOp;
218 }
219}
220
221/*
222** Return non-zero if opcode 'op' is guarenteed not to push more values
223** onto the VDBE stack than it pops off.
224*/
225static int opcodeNoPush(u8 op){
226 /* The 10 NOPUSH_MASK_n constants are defined in the automatically
227 ** generated header file opcodes.h. Each is a 16-bit bitmask, one
228 ** bit corresponding to each opcode implemented by the virtual
229 ** machine in vdbe.c. The bit is true if the word "no-push" appears
230 ** in a comment on the same line as the "case OP_XXX:" in
231 ** sqlite3VdbeExec() in vdbe.c.
232 **
233 ** If the bit is true, then the corresponding opcode is guarenteed not
234 ** to grow the stack when it is executed. Otherwise, it may grow the
235 ** stack by at most one entry.
236 **
237 ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains
238 ** one bit for opcodes 16 to 31, and so on.
239 **
240 ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h
241 ** because the file is generated by an awk program. Awk manipulates
242 ** all numbers as floating-point and we don't want to risk a rounding
243 ** error if someone builds with an awk that uses (for example) 32-bit
244 ** IEEE floats.
245 */
246 static const u32 masks[5] = {
247 NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16),
248 NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16),
249 NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16),
250 NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16),
251 NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
252 };
253 assert( op<32*5 );
254 return (masks[op>>5] & (1<<(op&0x1F)));
255}
256
257#ifndef NDEBUG
258int sqlite3VdbeOpcodeNoPush(u8 op){
259 return opcodeNoPush(op);
260}
261#endif
262
263/*
264** Loop through the program looking for P2 values that are negative.
265** Each such value is a label. Resolve the label by setting the P2
266** value to its correct non-zero value.
267**
268** This routine is called once after all opcodes have been inserted.
269**
270** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
271** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
272** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
273**
274** The integer *pMaxStack is set to the maximum number of vdbe stack

417/*
418** If the input FuncDef structure is ephemeral, then free it. If
419** the FuncDef is not ephermal, then do nothing.
420*/
421static void freeEphemeralFunction(FuncDef *pDef){
422 if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
423 sqliteFree(pDef);
424 }
425}
426
427/*
428** Delete a P3 value if necessary.
429*/
430static void freeP3(int p3type, void *p3){
431 if( p3 ){
432 switch( p3type ){
433 case P3_DYNAMIC:
434 case P3_KEYINFO:
435 case P3_KEYINFO_HANDOFF: {
436 sqliteFree(p3);
437 break;
438 }
439 case P3_MPRINTF: {
440 sqlite3_free(p3);
441 break;
442 }
443 case P3_VDBEFUNC: {
444 VdbeFunc *pVdbeFunc = (VdbeFunc *)p3;
445 freeEphemeralFunction(pVdbeFunc->pFunc);
446 sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
447 sqliteFree(pVdbeFunc);
448 break;
449 }
450 case P3_FUNCDEF: {
451 freeEphemeralFunction((FuncDef*)p3);
452 break;
453 }
454 case P3_MEM: {
455 sqlite3ValueFree((sqlite3_value*)p3);
456 break;
457 }
458 }
459 }
460}
461
462
463/*
464** Change N opcodes starting at addr to No-ops.
465*/
466void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
467 VdbeOp *pOp = &p->aOp[addr];
468 while( N-- ){
469 freeP3(pOp->p3type, pOp->p3);
470 memset(pOp, 0, sizeof(pOp[0]));
471 pOp->opcode = OP_Noop;
472 pOp++;
473 }
474}

569/*
570** Return the opcode for a given address.
571*/
572VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
573 assert( p->magic==VDBE_MAGIC_INIT );
574 assert( addr>=0 && addr<p->nOp );
575 return &p->aOp[addr];
576}
577
578#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
579 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
580/*
581** Compute a string that describes the P3 parameter for an opcode.
582** Use zTemp for any required temporary buffer space.
583*/
584static char *displayP3(Op *pOp, char *zTemp, int nTemp){
585 char *zP3;
586 assert( nTemp>=20 );
587 switch( pOp->p3type ){
588 case P3_KEYINFO: {
589 int i, j;
590 KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3;
591 sprintf(zTemp, "keyinfo(%d", pKeyInfo->nField);
592 i = strlen(zTemp);
593 for(j=0; j<pKeyInfo->nField; j++){
594 CollSeq *pColl = pKeyInfo->aColl[j];
595 if( pColl ){
596 int n = strlen(pColl->zName);
597 if( i+n>nTemp-6 ){
598 strcpy(&zTemp[i],",...");
599 break;
600 }
601 zTemp[i++] = ',';

624 case P3_FUNCDEF: {
625 FuncDef *pDef = (FuncDef*)pOp->p3;
626 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
627 zP3 = zTemp;
628 break;
629 }
630#ifndef SQLITE_OMIT_VIRTUALTABLE
631 case P3_VTAB: {
632 sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3;
633 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
634 zP3 = zTemp;
635 break;
636 }
637#endif
638 default: {
639 zP3 = pOp->p3;
640 if( zP3==0 || pOp->opcode==OP_Noop ){
641 zP3 = "";
642 }
643 }
644 }
645 assert( zP3!=0 );
646 return zP3;
647}
648#endif
649
650
651#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
652/*
653** Print a single opcode. This routine is used for debugging only.
654*/
655void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
656 char *zP3;
657 char zPtr[50];
658 static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
659 if( pOut==0 ) pOut = stdout;
660 zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
661 fprintf(pOut, zFormat1,
662 pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
663 fflush(pOut);
664}
665#endif
666
667/*
668** Release an array of N Mem elements
669*/
670static void releaseMemArray(Mem *p, int N){
671 if( p ){
672 while( N-->0 ){
673 sqlite3VdbeMemRelease(p++);
674 }
675 }
676}
677
678#ifndef SQLITE_OMIT_EXPLAIN
679/*
680** Give a listing of the program in the virtual machine.
681**
682** The interface is the same as sqlite3VdbeExec(). But instead of
683** running the code, it invokes the callback once for each instruction.
684** This feature is used to implement "EXPLAIN".
685*/
686int sqlite3VdbeList(
687 Vdbe *p /* The VDBE */
688){
689 sqlite3 *db = p->db;
690 int i;

748 pMem->enc = SQLITE_UTF8;
749
750 p->nResColumn = 5 - 2*(p->explain-1);
751 p->pTos = pMem;
752 p->rc = SQLITE_OK;
753 p->resOnStack = 1;
754 rc = SQLITE_ROW;
755 }
756 return rc;
757}
758#endif /* SQLITE_OMIT_EXPLAIN */
759
760/*
761** Print the SQL that was used to generate a VDBE program.
762*/
763void sqlite3VdbePrintSql(Vdbe *p){
764#ifdef SQLITE_DEBUG
765 int nOp = p->nOp;
766 VdbeOp *pOp;
767 if( nOp<1 ) return;
768 pOp = &p->aOp[nOp-1];
769 if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
770 const char *z = pOp->p3;
771 while( isspace(*(u8*)z) ) z++;
772 printf("SQL: [%s]\n", z);
773 }
774#endif
775}
776
777/*
778** Prepare a virtual machine for execution. This involves things such
779** as allocating stack space and initializing the program counter.
780** After the VDBE has be prepped, it can be executed by one or more
781** calls to sqlite3VdbeExec().
782**
783** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
784** VDBE_MAGIC_RUN.
785*/
786void sqlite3VdbeMakeReady(
787 Vdbe *p, /* The VDBE */
788 int nVar, /* Number of '?' see in the SQL statement */
789 int nMem, /* Number of memory cells to allocate */

868 {
869 int i;
870 for(i=0; i<p->nOp; i++){
871 p->aOp[i].cnt = 0;
872 p->aOp[i].cycles = 0;
873 }
874 }
875#endif
876}
877
878/*
879** Close a cursor and release all the resources that cursor happens
880** to hold.
881*/
882void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
883 if( pCx==0 ){
884 return;
885 }
886 if( pCx->pCursor ){
887 sqlite3BtreeCloseCursor(pCx->pCursor);
888 }
889 if( pCx->pBt ){
890 sqlite3BtreeClose(pCx->pBt);
891 }
892#ifndef SQLITE_OMIT_VIRTUALTABLE
893 if( pCx->pVtabCursor ){
894 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
895 const sqlite3_module *pModule = pCx->pModule;
896 p->inVtabMethod = 1;
897 sqlite3SafetyOff(p->db);
898 pModule->xClose(pVtabCursor);
899 sqlite3SafetyOn(p->db);
900 p->inVtabMethod = 0;
901 }
902#endif
903 sqliteFree(pCx->pData);
904 sqliteFree(pCx->aType);
905 sqliteFree(pCx);
906}
907
908/*
909** Close all cursors
910*/
911static void closeAllCursors(Vdbe *p){
912 int i;
913 if( p->apCsr==0 ) return;
914 for(i=0; i<p->nCursor; i++){
915 if( !p->inVtabMethod || (p->apCsr[i] && !p->apCsr[i]->pVtabCursor) ){
916 sqlite3VdbeFreeCursor(p, p->apCsr[i]);
917 p->apCsr[i] = 0;
918 }
919 }
920}
921
922/*
923** Clean up the VM after execution.
924**
925** This routine will automatically close any cursors, lists, and/or
926** sorters that were left open. It also deletes the values of
927** variables in the aVar[] array.
928*/
929static void Cleanup(Vdbe *p){
930 int i;
931 if( p->aStack ){
932 releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack));
933 p->pTos = &p->aStack[-1];
934 }
935 closeAllCursors(p);
936 releaseMemArray(p->aMem, p->nMem);
937 sqlite3VdbeFifoClear(&p->sFifo);
938 if( p->contextStack ){
939 for(i=0; i<p->contextStackTop; i++){
940 sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
941 }
942 sqliteFree(p->contextStack);
943 }
944 p->contextStack = 0;
945 p->contextStackDepth = 0;
946 p->contextStackTop = 0;
947 sqliteFree(p->zErrMsg);
948 p->zErrMsg = 0;
949}
950
951/*
952** Set the number of result columns that will be returned by this SQL
953** statement. This is now set at compile time, rather than during
954** execution of the vdbe program so that sqlite3_column_count() can
955** be called on an SQL statement before sqlite3_step().
956*/
957void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
958 Mem *pColName;
959 int n;
960 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
961 sqliteFree(p->aColName);
962 n = nResColumn*COLNAME_N;
963 p->nResColumn = nResColumn;

1205#endif
1206
1207 return rc;
1208}
1209
1210/*
1211** This routine checks that the sqlite3.activeVdbeCnt count variable
1212** matches the number of vdbe's in the list sqlite3.pVdbe that are
1213** currently active. An assertion fails if the two counts do not match.
1214** This is an internal self-check only - it is not an essential processing
1215** step.
1216**
1217** This is a no-op if NDEBUG is defined.
1218*/
1219#ifndef NDEBUG
1220static void checkActiveVdbeCnt(sqlite3 *db){
1221 Vdbe *p;
1222 int cnt = 0;
1223 p = db->pVdbe;
1224 while( p ){
1225 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
1226 cnt++;
1227 }
1228 p = p->pNext;
1229 }
1230 assert( cnt==db->activeVdbeCnt );
1231}
1232#else
1233#define checkActiveVdbeCnt(x)
1234#endif
1235
1236/*
1237** Find every active VM other than pVdbe and change its status to
1238** aborted. This happens when one VM causes a rollback due to an
1239** ON CONFLICT ROLLBACK clause (for example). The other VMs must be
1240** aborted so that they do not have data rolled out from underneath
1241** them leading to a segfault.
1242*/
1243void sqlite3AbortOtherActiveVdbes(sqlite3 *db, Vdbe *pExcept){
1244 Vdbe *pOther;
1245 for(pOther=db->pVdbe; pOther; pOther=pOther->pNext){

1252 }
1253}
1254
1255/*
1256** This routine is called the when a VDBE tries to halt. If the VDBE
1257** has made changes and is in autocommit mode, then commit those
1258** changes. If a rollback is needed, then do the rollback.
1259**
1260** This routine is the only way to move the state of a VM from
1261** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
1262**
1263** Return an error code. If the commit could not complete because of
1264** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
1265** means the close did not happen and needs to be repeated.
1266*/
1267int sqlite3VdbeHalt(Vdbe *p){
1268 sqlite3 *db = p->db;
1269 int i;
1270 int (*xFunc)(Btree *pBt) = 0; /* Function to call on each btree backend */
1271 int isSpecialError; /* Set to true if SQLITE_NOMEM or IOERR */
1272
1273 /* This function contains the logic that determines if a statement or
1274 ** transaction will be committed or rolled back as a result of the
1275 ** execution of this virtual machine.
1276 **
1277 ** Special errors:
1278 **
1279 ** If an SQLITE_NOMEM error has occured in a statement that writes to
1280 ** the database, then either a statement or transaction must be rolled
1281 ** back to ensure the tree-structures are in a consistent state. A
1282 ** statement transaction is rolled back if one is open, otherwise the

1286 ** the database, then the entire transaction must be rolled back. The
1287 ** I/O error may have caused garbage to be written to the journal
1288 ** file. Were the transaction to continue and eventually be rolled
1289 ** back that garbage might end up in the database file.
1290 **
1291 ** In both of the above cases, the Vdbe.errorAction variable is
1292 ** ignored. If the sqlite3.autoCommit flag is false and a transaction
1293 ** is rolled back, it will be set to true.
1294 **
1295 ** Other errors:
1296 **
1297 ** No error:
1298 **
1299 */
1300
1301 if( sqlite3MallocFailed() ){
1302 p->rc = SQLITE_NOMEM;
1303 }
1304 if( p->magic!=VDBE_MAGIC_RUN ){
1305 /* Already halted. Nothing to do. */
1306 assert( p->magic==VDBE_MAGIC_HALT );
1307#ifndef SQLITE_OMIT_VIRTUALTABLE
1308 closeAllCursors(p);
1309#endif
1310 return SQLITE_OK;
1311 }
1312 closeAllCursors(p);
1313 checkActiveVdbeCnt(db);
1314
1315 /* No commit or rollback needed if the program never started */
1316 if( p->pc>=0 ){
1317 int mrc; /* Primary error code from p->rc */
1318 /* Check for one of the special errors - SQLITE_NOMEM or SQLITE_IOERR */
1319 mrc = p->rc & 0xff;
1320 isSpecialError = ((mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR)?1:0);
1321 if( isSpecialError ){
1322 /* This loop does static analysis of the query to see which of the
1323 ** following three categories it falls into:
1324 **
1325 ** Read-only
1326 ** Query with statement journal
1327 ** Query without statement journal
1328 **
1329 ** We could do something more elegant than this static analysis (i.e.
1330 ** store the type of query as part of the compliation phase), but
1331 ** handling malloc() or IO failure is a fairly obscure edge case so
1332 ** this is probably easier. Todo: Might be an opportunity to reduce
1333 ** code size a very small amount though...
1334 */
1335 int isReadOnly = 1;

1346 }
1347 }
1348
1349 /* If the query was read-only, we need do no rollback at all. Otherwise,
1350 ** proceed with the special handling.
1351 */
1352 if( !isReadOnly ){
1353 if( p->rc==SQLITE_NOMEM && isStatement ){
1354 xFunc = sqlite3BtreeRollbackStmt;
1355 }else{
1356 /* We are forced to roll back the active transaction. Before doing
1357 ** so, abort any other statements this handle currently has active.
1358 */
1359 sqlite3AbortOtherActiveVdbes(db, p);
1360 sqlite3RollbackAll(db);
1361 db->autoCommit = 1;
1362 }
1363 }
1364 }
1365
1366 /* If the auto-commit flag is set and this is the only active vdbe, then
1367 ** we do either a commit or rollback of the current transaction.
1368 **
1369 ** Note: This block also runs if one of the special errors handled
1370 ** above has occured.
1371 */
1372 if( db->autoCommit && db->activeVdbeCnt==1 ){
1373 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
1374 /* The auto-commit flag is true, and the vdbe program was
1375 ** successful or hit an 'OR FAIL' constraint. This means a commit
1376 ** is required.
1377 */
1378 int rc = vdbeCommit(db);
1379 if( rc==SQLITE_BUSY ){
1380 return SQLITE_BUSY;
1381 }else if( rc!=SQLITE_OK ){
1382 p->rc = rc;
1383 sqlite3RollbackAll(db);
1384 }else{
1385 sqlite3CommitInternalChanges(db);
1386 }
1387 }else{
1388 sqlite3RollbackAll(db);
1389 }
1390 }else if( !xFunc ){
1391 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
1392 xFunc = sqlite3BtreeCommitStmt;
1393 }else if( p->errorAction==OE_Abort ){
1394 xFunc = sqlite3BtreeRollbackStmt;
1395 }else{
1396 sqlite3AbortOtherActiveVdbes(db, p);
1397 sqlite3RollbackAll(db);
1398 db->autoCommit = 1;
1399 }
1400 }
1401
1402 /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
1403 ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
1404 ** and the return code is still SQLITE_OK, set the return code to the new
1405 ** error value.
1406 */
1407 assert(!xFunc ||
1408 xFunc==sqlite3BtreeCommitStmt ||
1409 xFunc==sqlite3BtreeRollbackStmt
1410 );
1411 for(i=0; xFunc && i<db->nDb; i++){
1412 int rc;
1413 Btree *pBt = db->aDb[i].pBt;
1414 if( pBt ){
1415 rc = xFunc(pBt);
1416 if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
1417 p->rc = rc;
1418 sqlite3SetString(&p->zErrMsg, 0);
1419 }
1420 }
1421 }
1422
1423 /* If this was an INSERT, UPDATE or DELETE and the statement was committed,
1424 ** set the change counter.
1425 */
1426 if( p->changeCntOn && p->pc>=0 ){
1427 if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
1428 sqlite3VdbeSetChanges(db, p->nChange);
1429 }else{
1430 sqlite3VdbeSetChanges(db, 0);
1431 }
1432 p->nChange = 0;
1433 }
1434
1435 /* Rollback or commit any schema changes that occurred. */
1436 if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
1437 sqlite3ResetInternalSchema(db, 0);
1438 db->flags = (db->flags | SQLITE_InternChanges);
1439 }
1440 }
1441
1442 /* We have successfully halted and closed the VM. Record this fact. */
1443 if( p->pc>=0 ){
1444 db->activeVdbeCnt--;
1445 }
1446 p->magic = VDBE_MAGIC_HALT;
1447 checkActiveVdbeCnt(db);
1448
1449 return SQLITE_OK;
1450}
1451
1452/*
1453** Each VDBE holds the result of the most recent sqlite3_step() call
1454** in p->rc. This routine sets that result back to SQLITE_OK.
1455*/
1456void sqlite3VdbeResetStepResult(Vdbe *p){
1457 p->rc = SQLITE_OK;
1458}
1459
1460/*
1461** Clean up a VDBE after execution but do not delete the VDBE just yet.
1462** Write any error messages into *pzErrMsg. Return the result code.
1463**
1464** After this routine is run, the VDBE should be ready to be executed
1465** again.
1466**
1467** To look at it another way, this routine resets the state of the
1468** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
1469** VDBE_MAGIC_INIT.
1470*/
1471int sqlite3VdbeReset(Vdbe *p){
1472 sqlite3 *db;
1473 if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
1474 sqlite3Error(p->db, SQLITE_MISUSE, 0);
1475 return SQLITE_MISUSE;
1476 }
1477 db = p->db;
1478
1479 /* If the VM did not run to completion or if it encountered an
1480 ** error, then it might not have been halted properly. So halt
1481 ** it now.
1482 */
1483 sqlite3SafetyOn(db);
1484 sqlite3VdbeHalt(p);
1485 sqlite3SafetyOff(db);
1486
1487 /* If the VDBE has be run even partially, then transfer the error code
1488 ** and error message from the VDBE into the main database structure. But
1489 ** if the VDBE has just been set to run but has not actually executed any
1490 ** instructions yet, leave the main database error information unchanged.
1491 */
1492 if( p->pc>=0 ){
1493 if( p->zErrMsg ){
1494 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, sqlite3FreeX);
1495 db->errCode = p->rc;
1496 p->zErrMsg = 0;
1497 }else if( p->rc ){
1498 sqlite3Error(db, p->rc, 0);
1499 }else{
1500 sqlite3Error(db, SQLITE_OK, 0);
1501 }
1502 }else if( p->rc && p->expired ){
1503 /* The expired flag was set on the VDBE before the first call
1504 ** to sqlite3_step(). For consistency (since sqlite3_step() was
1505 ** called), set the database error in this case as well.
1506 */
1507 sqlite3Error(db, p->rc, 0);
1508 }
1509
1510 /* Reclaim all memory used by the VDBE
1511 */
1512 Cleanup(p);
1513
1514 /* Save profiling information from this VDBE run.
1515 */
1516 assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack );
1517#ifdef VDBE_PROFILE
1518 {
1519 FILE *out = fopen("vdbe_profile.out", "a");
1520 if( out ){
1521 int i;
1522 fprintf(out, "---- ");
1523 for(i=0; i<p->nOp; i++){
1524 fprintf(out, "%02x", p->aOp[i].opcode);
1525 }
1526 fprintf(out, "\n");
1527 for(i=0; i<p->nOp; i++){
1528 fprintf(out, "%6d %10lld %8lld ",
1529 p->aOp[i].cnt,
1530 p->aOp[i].cycles,
1531 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
1532 );
1533 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
1534 }
1535 fclose(out);
1536 }
1537 }
1538#endif
1539 p->magic = VDBE_MAGIC_INIT;
1540 p->aborted = 0;
1541 if( p->rc==SQLITE_SCHEMA ){
1542 sqlite3ResetInternalSchema(db, 0);
1543 }
1544 return p->rc & db->errMask;
1545}
1546
1547/*
1548** Clean up and delete a VDBE after execution. Return an integer which is
1549** the result code. Write any error message text into *pzErrMsg.
1550*/
1551int sqlite3VdbeFinalize(Vdbe *p){
1552 int rc = SQLITE_OK;
1553 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
1554 rc = sqlite3VdbeReset(p);
1555 assert( (rc & p->db->errMask)==rc );
1556 }else if( p->magic!=VDBE_MAGIC_INIT ){
1557 return SQLITE_MISUSE;
1558 }
1559 sqlite3VdbeDelete(p);
1560 return rc;
1561}
1562
1563/*
1564** Call the destructor for each auxdata entry in pVdbeFunc for which
1565** the corresponding bit in mask is clear. Auxdata entries beyond 31
1566** are always destroyed. To destroy all auxdata entries, call this
1567** routine with mask==0.
1568*/
1569void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
1570 int i;
1571 for(i=0; i<pVdbeFunc->nAux; i++){
1572 struct AuxData *pAux = &pVdbeFunc->apAux[i];
1573 if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
1574 if( pAux->xDelete ){
1575 pAux->xDelete(pAux->pAux);
1576 }
1577 pAux->pAux = 0;
1578 }
1579 }
1580}
1581
1582/*
1583** Delete an entire VDBE.
1584*/
1585void sqlite3VdbeDelete(Vdbe *p){
1586 int i;
1587 if( p==0 ) return;
1588 Cleanup(p);
1589 if( p->pPrev ){
1590 p->pPrev->pNext = p->pNext;
1591 }else{
1592 assert( p->db->pVdbe==p );
1593 p->db->pVdbe = p->pNext;
1594 }
1595 if( p->pNext ){
1596 p->pNext->pPrev = p->pPrev;
1597 }
1598 if( p->aOp ){
1599 for(i=0; i<p->nOp; i++){
1600 Op *pOp = &p->aOp[i];
1601 freeP3(pOp->p3type, pOp->p3);
1602 }
1603 sqliteFree(p->aOp);
1604 }
1605 releaseMemArray(p->aVar, p->nVar);
1606 sqliteFree(p->aLabel);
1607 sqliteFree(p->aStack);
1608 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
1609 sqliteFree(p->aColName);
1610 sqliteFree(p->zSql);
1611 p->magic = VDBE_MAGIC_DEAD;
1612 sqliteFree(p);
1613}
1614
1615/*
1616** If a MoveTo operation is pending on the given cursor, then do that
1617** MoveTo now. Return an error code. If no MoveTo is pending, this
1618** routine does nothing and returns SQLITE_OK.
1619*/
1620int sqlite3VdbeCursorMoveto(Cursor *p){
1621 if( p->deferredMoveto ){
1622 int res, rc;
1623#ifdef SQLITE_TEST
1624 extern int sqlite3_search_count;
1625#endif
1626 assert( p->isTable );
1627 if( p->isTable ){

./src/vdbefifo.c

25 nEntry = 32767;
26 }
27 pPage = sqliteMallocRaw( sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
28 if( pPage ){
29 pPage->nSlot = nEntry;
30 pPage->iWrite = 0;
31 pPage->iRead = 0;
32 pPage->pNext = 0;
33 }
34 return pPage;
35}
36
37/*
38** Initialize a Fifo structure.
39*/
40void sqlite3VdbeFifoInit(Fifo *pFifo){
41 memset(pFifo, 0, sizeof(*pFifo));
42}
43
44/*
45** Push a single 64-bit integer value into the Fifo. Return SQLITE_OK
46** normally. SQLITE_NOMEM is returned if we are unable to allocate
47** memory.
48*/
49int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
50 FifoPage *pPage;
51 pPage = pFifo->pLast;
52 if( pPage==0 ){
53 pPage = pFifo->pLast = pFifo->pFirst = allocatePage(20);
54 if( pPage==0 ){
55 return SQLITE_NOMEM;
56 }

94 }else{
95 assert( pFifo->pFirst!=0 );
96 }
97 }else{
98 assert( pFifo->nEntry>0 );
99 }
100 return SQLITE_OK;
101}
102
103/*
104** Delete all information from a Fifo object. Free all memory held
105** by the Fifo.
106*/
107void sqlite3VdbeFifoClear(Fifo *pFifo){
108 FifoPage *pPage, *pNextPage;
109 for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
110 pNextPage = pPage->pNext;
111 sqliteFree(pPage);
112 }
113 sqlite3VdbeFifoInit(pFifo);
114}

./src/os_unix.c

778# define transferOwnership(X) SQLITE_OK
779#endif
780
781/*
782** Delete the named file
783*/
784int sqlite3UnixDelete(const char *zFilename){
785 unlink(zFilename);
786 return SQLITE_OK;
787}
788
789/*
790** Return TRUE if the named file exists.
791*/
792int sqlite3UnixFileExists(const char *zFilename){
793 return access(zFilename, 0)==0;
794}
795
796/* Forward declaration */
797static int allocateUnixFile(
798 int h, /* File descriptor of the open file */
799 OsFile **pId, /* Write the real file descriptor here */
800 const char *zFilename, /* Name of the file being opened */
801 int delFlag /* If true, make sure the file deletes on close */
802);
803
804/*
805** Attempt to open a file for both reading and writing. If that
806** fails, try opening it read-only. If the file does not exist,
807** try to create it.
808**

./src/vdbemem.c

210 pMem->z = pMem->zShort;
211 }
212 if( ctx.isError ){
213 rc = SQLITE_ERROR;
214 }
215 }
216 return rc;
217}
218
219/*
220** Release any memory held by the Mem. This may leave the Mem in an
221** inconsistent state, for example with (Mem.z==0) and
222** (Mem.type==SQLITE_TEXT).
223*/
224void sqlite3VdbeMemRelease(Mem *p){
225 if( p->flags & (MEM_Dyn|MEM_Agg) ){
226 if( p->xDel ){
227 if( p->flags & MEM_Agg ){
228 sqlite3VdbeMemFinalize(p, *(FuncDef**)&p->i);
229 assert( (p->flags & MEM_Agg)==0 );
230 sqlite3VdbeMemRelease(p);
231 }else{
232 p->xDel((void *)p->z);
233 }
234 }else{
235 sqliteFree(p->z);
236 }
237 p->z = 0;
238 p->xDel = 0;
239 }
240}
241
242/*
243** Return some kind of integer value which is the best we can do
244** at representing the value that *pMem describes as an integer.
245** If pMem is an integer, then the value is exact. If pMem is
246** a floating-point then the value returned is the integer part.
247** If pMem is a string or blob, then we make an attempt to convert
248** it into a integer and return that. If pMem is NULL, return 0.
249**
250** If pMem is a string, its encoding might be changed.
251*/
252i64 sqlite3VdbeIntValue(Mem *pMem){
253 int flags = pMem->flags;
254 if( flags & MEM_Int ){

427 }else{
428 rc = SQLITE_OK;
429 }
430 return rc;
431}
432
433/*
434** Change the value of a Mem to be a string or a BLOB.
435*/
436int sqlite3VdbeMemSetStr(
437 Mem *pMem, /* Memory cell to set to string value */
438 const char *z, /* String pointer */
439 int n, /* Bytes in string, or negative */
440 u8 enc, /* Encoding of z. 0 for BLOBs */
441 void (*xDel)(void*) /* Destructor function */
442){
443 sqlite3VdbeMemRelease(pMem);
444 if( !z ){
445 pMem->flags = MEM_Null;
446 pMem->type = SQLITE_NULL;
447 return SQLITE_OK;
448 }
449
450 pMem->z = (char *)z;
451 if( xDel==SQLITE_STATIC ){
452 pMem->flags = MEM_Static;
453 }else if( xDel==SQLITE_TRANSIENT ){
454 pMem->flags = MEM_Ephem;
455 }else{
456 pMem->flags = MEM_Dyn;
457 pMem->xDel = xDel;
458 }
459
460 pMem->enc = enc;
461 pMem->type = enc==0 ? SQLITE_BLOB : SQLITE_TEXT;
462 pMem->n = n;
463
464 assert( enc==0 || enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE
465 || enc==SQLITE_UTF16BE );
466 switch( enc ){
467 case 0:
468 pMem->flags |= MEM_Blob;
469 pMem->enc = SQLITE_UTF8;
470 break;
471
472 case SQLITE_UTF8:
473 pMem->flags |= MEM_Str;
474 if( n<0 ){
475 pMem->n = strlen(z);
476 pMem->flags |= MEM_Term;
477 }
478 break;
479
480#ifndef SQLITE_OMIT_UTF16
481 case SQLITE_UTF16LE:
482 case SQLITE_UTF16BE:
483 pMem->flags |= MEM_Str;
484 if( pMem->n<0 ){
485 pMem->n = sqlite3utf16ByteLen(pMem->z,-1);
486 pMem->flags |= MEM_Term;
487 }
488 if( sqlite3VdbeMemHandleBom(pMem) ){
489 return SQLITE_NOMEM;
490 }
491#endif /* SQLITE_OMIT_UTF16 */
492 }
493 if( pMem->flags&MEM_Ephem ){
494 return sqlite3VdbeMemMakeWriteable(pMem);
495 }
496 return SQLITE_OK;
497}
498
499/*
500** Compare the values contained by the two memory cells, returning
501** negative, zero or positive if pMem1 is less than, equal to, or greater
502** than pMem2. Sorting order is NULL's first, followed by numbers (integers
503** and reals) sorted numerically, followed by text ordered by the collating
504** sequence pColl and finally blob's ordered by memcmp().
505**
506** Two NULL values are considered equal by this function.
507*/
508int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
509 int rc;
510 int f1, f2;
511 int combined_flags;

855 sqliteFree(zVal);
856 sqlite3ValueFree(pVal);
857 *ppVal = 0;
858 return SQLITE_NOMEM;
859}
860
861/*
862** Change the string value of an sqlite3_value object
863*/
864void sqlite3ValueSetStr(
865 sqlite3_value *v,
866 int n,
867 const void *z,
868 u8 enc,
869 void (*xDel)(void*)
870){
871 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
872}
873
874/*
875** Free an sqlite3_value object
876*/
877void sqlite3ValueFree(sqlite3_value *v){
878 if( !v ) return;
879 sqlite3ValueSetStr(v, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
880 sqliteFree(v);
881}
882
883/*
884** Return the number of bytes in the sqlite3_value object assuming
885** that it uses the encoding "enc"
886*/