Fixes default log output to console for macOS
[sqlcipher.git] / test / fuzzcheck.c
blob6cae348bd64817903e48d146bb3c92d30a3d9b9d
1 /*
2 ** 2015-05-25
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.
11 *************************************************************************
13 ** This is a utility program designed to aid running regressions tests on
14 ** the SQLite library using data from external fuzzers.
16 ** This program reads content from an SQLite database file with the following
17 ** schema:
19 ** CREATE TABLE db(
20 ** dbid INTEGER PRIMARY KEY, -- database id
21 ** dbcontent BLOB -- database disk file image
22 ** );
23 ** CREATE TABLE xsql(
24 ** sqlid INTEGER PRIMARY KEY, -- SQL script id
25 ** sqltext TEXT -- Text of SQL statements to run
26 ** );
27 ** CREATE TABLE IF NOT EXISTS readme(
28 ** msg TEXT -- Human-readable description of this test collection
29 ** );
31 ** For each database file in the DB table, the SQL text in the XSQL table
32 ** is run against that database. All README.MSG values are printed prior
33 ** to the start of the test (unless the --quiet option is used). If the
34 ** DB table is empty, then all entries in XSQL are run against an empty
35 ** in-memory database.
37 ** This program is looking for crashes, assertion faults, and/or memory leaks.
38 ** No attempt is made to verify the output. The assumption is that either all
39 ** of the database files or all of the SQL statements are malformed inputs,
40 ** generated by a fuzzer, that need to be checked to make sure they do not
41 ** present a security risk.
43 ** This program also includes some command-line options to help with
44 ** creation and maintenance of the source content database. The command
46 ** ./fuzzcheck database.db --load-sql FILE...
48 ** Loads all FILE... arguments into the XSQL table. The --load-db option
49 ** works the same but loads the files into the DB table. The -m option can
50 ** be used to initialize the README table. The "database.db" file is created
51 ** if it does not previously exist. Example:
53 ** ./fuzzcheck new.db --load-sql *.sql
54 ** ./fuzzcheck new.db --load-db *.db
55 ** ./fuzzcheck new.db -m 'New test cases'
57 ** The three commands above will create the "new.db" file and initialize all
58 ** tables. Then do "./fuzzcheck new.db" to run the tests.
60 ** DEBUGGING HINTS:
62 ** If fuzzcheck does crash, it can be run in the debugger and the content
63 ** of the global variable g.zTextName[] will identify the specific XSQL and
64 ** DB values that were running when the crash occurred.
66 ** DBSQLFUZZ: (Added 2020-02-25)
68 ** The dbsqlfuzz fuzzer includes both a database file and SQL to run against
69 ** that database in its input. This utility can now process dbsqlfuzz
70 ** input files. Load such files using the "--load-dbsql FILE ..." command-line
71 ** option.
73 ** Dbsqlfuzz inputs are ordinary text. The first part of the file is text
74 ** that describes the content of the database (using a lot of hexadecimal),
75 ** then there is a divider line followed by the SQL to run against the
76 ** database. Because they are ordinary text, dbsqlfuzz inputs are stored
77 ** in the XSQL table, as if they were ordinary SQL inputs. The isDbSql()
78 ** function can look at a text string and determine whether or not it is
79 ** a valid dbsqlfuzz input.
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <stdarg.h>
85 #include <ctype.h>
86 #include <assert.h>
87 #include "sqlite3.h"
88 #include "sqlite3recover.h"
89 #define ISSPACE(X) isspace((unsigned char)(X))
90 #define ISDIGIT(X) isdigit((unsigned char)(X))
93 #ifdef __unix__
94 # include <signal.h>
95 # include <unistd.h>
96 #endif
98 #include <stddef.h>
99 #if !defined(_MSC_VER)
100 # include <stdint.h>
101 #endif
103 #if defined(_MSC_VER)
104 typedef unsigned char uint8_t;
105 #endif
108 ** Files in the virtual file system.
110 typedef struct VFile VFile;
111 struct VFile {
112 char *zFilename; /* Filename. NULL for delete-on-close. From malloc() */
113 int sz; /* Size of the file in bytes */
114 int nRef; /* Number of references to this file */
115 unsigned char *a; /* Content of the file. From malloc() */
117 typedef struct VHandle VHandle;
118 struct VHandle {
119 sqlite3_file base; /* Base class. Must be first */
120 VFile *pVFile; /* The underlying file */
124 ** The value of a database file template, or of an SQL script
126 typedef struct Blob Blob;
127 struct Blob {
128 Blob *pNext; /* Next in a list */
129 int id; /* Id of this Blob */
130 int seq; /* Sequence number */
131 int sz; /* Size of this Blob in bytes */
132 unsigned char a[1]; /* Blob content. Extra space allocated as needed. */
136 ** Maximum number of files in the in-memory virtual filesystem.
138 #define MX_FILE 10
141 ** Maximum allowed file size
143 #define MX_FILE_SZ 10000000
146 ** All global variables are gathered into the "g" singleton.
148 static struct GlobalVars {
149 const char *zArgv0; /* Name of program */
150 const char *zDbFile; /* Name of database file */
151 VFile aFile[MX_FILE]; /* The virtual filesystem */
152 int nDb; /* Number of template databases */
153 Blob *pFirstDb; /* Content of first template database */
154 int nSql; /* Number of SQL scripts */
155 Blob *pFirstSql; /* First SQL script */
156 unsigned int uRandom; /* Seed for the SQLite PRNG */
157 unsigned int nInvariant; /* Number of invariant checks run */
158 char zTestName[100]; /* Name of current test */
159 } g;
162 ** Include the external vt02.c and randomjson.c modules.
164 extern int sqlite3_vt02_init(sqlite3*,char**,const sqlite3_api_routines*);
165 extern int sqlite3_randomjson_init(sqlite3*,char**,const sqlite3_api_routines*);
169 ** Print an error message and quit.
171 static void fatalError(const char *zFormat, ...){
172 va_list ap;
173 fprintf(stderr, "%s", g.zArgv0);
174 if( g.zDbFile ) fprintf(stderr, " %s", g.zDbFile);
175 if( g.zTestName[0] ) fprintf(stderr, " (%s)", g.zTestName);
176 fprintf(stderr, ": ");
177 va_start(ap, zFormat);
178 vfprintf(stderr, zFormat, ap);
179 va_end(ap);
180 fprintf(stderr, "\n");
181 exit(1);
185 ** signal handler
187 #ifdef __unix__
188 static void signalHandler(int signum){
189 const char *zSig;
190 if( signum==SIGABRT ){
191 zSig = "abort";
192 }else if( signum==SIGALRM ){
193 zSig = "timeout";
194 }else if( signum==SIGSEGV ){
195 zSig = "segfault";
196 }else{
197 zSig = "signal";
199 fatalError(zSig);
201 #endif
204 ** Set the an alarm to go off after N seconds. Disable the alarm
205 ** if N==0
207 static void setAlarm(int N){
208 #ifdef __unix__
209 alarm(N);
210 #else
211 (void)N;
212 #endif
215 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
217 ** This an SQL progress handler. After an SQL statement has run for
218 ** many steps, we want to interrupt it. This guards against infinite
219 ** loops from recursive common table expressions.
221 ** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
222 ** In that case, hitting the progress handler is a fatal error.
224 static int progressHandler(void *pVdbeLimitFlag){
225 if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
226 return 1;
228 #endif
231 ** Reallocate memory. Show an error and quit if unable.
233 static void *safe_realloc(void *pOld, int szNew){
234 void *pNew = realloc(pOld, szNew<=0 ? 1 : szNew);
235 if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
236 return pNew;
240 ** Initialize the virtual file system.
242 static void formatVfs(void){
243 int i;
244 for(i=0; i<MX_FILE; i++){
245 g.aFile[i].sz = -1;
246 g.aFile[i].zFilename = 0;
247 g.aFile[i].a = 0;
248 g.aFile[i].nRef = 0;
254 ** Erase all information in the virtual file system.
256 static void reformatVfs(void){
257 int i;
258 for(i=0; i<MX_FILE; i++){
259 if( g.aFile[i].sz<0 ) continue;
260 if( g.aFile[i].zFilename ){
261 free(g.aFile[i].zFilename);
262 g.aFile[i].zFilename = 0;
264 if( g.aFile[i].nRef>0 ){
265 fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef);
267 g.aFile[i].sz = -1;
268 free(g.aFile[i].a);
269 g.aFile[i].a = 0;
270 g.aFile[i].nRef = 0;
275 ** Find a VFile by name
277 static VFile *findVFile(const char *zName){
278 int i;
279 if( zName==0 ) return 0;
280 for(i=0; i<MX_FILE; i++){
281 if( g.aFile[i].zFilename==0 ) continue;
282 if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
284 return 0;
288 ** Find a VFile by name. Create it if it does not already exist and
289 ** initialize it to the size and content given.
291 ** Return NULL only if the filesystem is full.
293 static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
294 VFile *pNew = findVFile(zName);
295 int i;
296 if( pNew ) return pNew;
297 for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
298 if( i>=MX_FILE ) return 0;
299 pNew = &g.aFile[i];
300 if( zName ){
301 int nName = (int)strlen(zName)+1;
302 pNew->zFilename = safe_realloc(0, nName);
303 memcpy(pNew->zFilename, zName, nName);
304 }else{
305 pNew->zFilename = 0;
307 pNew->nRef = 0;
308 pNew->sz = sz;
309 pNew->a = safe_realloc(0, sz);
310 if( sz>0 ) memcpy(pNew->a, pData, sz);
311 return pNew;
314 /* Return true if the line is all zeros */
315 static int allZero(unsigned char *aLine){
316 int i;
317 for(i=0; i<16 && aLine[i]==0; i++){}
318 return i==16;
322 ** Render a database and query as text that can be input into
323 ** the CLI.
325 static void renderDbSqlForCLI(
326 FILE *out, /* Write to this file */
327 const char *zFile, /* Name of the database file */
328 unsigned char *aDb, /* Database content */
329 int nDb, /* Number of bytes in aDb[] */
330 unsigned char *zSql, /* SQL content */
331 int nSql /* Bytes of SQL */
333 fprintf(out, ".print ******* %s *******\n", zFile);
334 if( nDb>100 ){
335 int i, j; /* Loop counters */
336 int pgsz; /* Size of each page */
337 int lastPage = 0; /* Last page number shown */
338 int iPage; /* Current page number */
339 unsigned char *aLine; /* Single line to display */
340 unsigned char buf[16]; /* Fake line */
341 unsigned char bShow[256]; /* Characters ok to display */
343 memset(bShow, '.', sizeof(bShow));
344 for(i=' '; i<='~'; i++){
345 if( i!='{' && i!='}' && i!='"' && i!='\\' ) bShow[i] = i;
347 pgsz = (aDb[16]<<8) | aDb[17];
348 if( pgsz==0 ) pgsz = 65536;
349 if( pgsz<512 || (pgsz&(pgsz-1))!=0 ) pgsz = 4096;
350 fprintf(out,".open --hexdb\n");
351 fprintf(out,"| size %d pagesize %d filename %s\n",nDb,pgsz,zFile);
352 for(i=0; i<nDb; i += 16){
353 if( i+16>nDb ){
354 memset(buf, 0, sizeof(buf));
355 memcpy(buf, aDb+i, nDb-i);
356 aLine = buf;
357 }else{
358 aLine = aDb + i;
360 if( allZero(aLine) ) continue;
361 iPage = i/pgsz + 1;
362 if( lastPage!=iPage ){
363 fprintf(out,"| page %d offset %d\n", iPage, (iPage-1)*pgsz);
364 lastPage = iPage;
366 fprintf(out,"| %5d:", i-(iPage-1)*pgsz);
367 for(j=0; j<16; j++) fprintf(out," %02x", aLine[j]);
368 fprintf(out," ");
369 for(j=0; j<16; j++){
370 unsigned char c = (unsigned char)aLine[j];
371 fputc( bShow[c], stdout);
373 fputc('\n', stdout);
375 fprintf(out,"| end %s\n", zFile);
376 }else{
377 fprintf(out,".open :memory:\n");
379 fprintf(out,".testctrl prng_seed 1 db\n");
380 fprintf(out,".testctrl internal_functions\n");
381 fprintf(out,"%.*s", nSql, zSql);
382 if( nSql>0 && zSql[nSql-1]!='\n' ) fprintf(out, "\n");
386 ** Read the complete content of a file into memory. Add a 0x00 terminator
387 ** and return a pointer to the result.
389 ** The file content is held in memory obtained from sqlite_malloc64() which
390 ** should be freed by the caller.
392 static char *readFile(const char *zFilename, long *sz){
393 FILE *in;
394 long nIn;
395 unsigned char *pBuf;
397 *sz = 0;
398 if( zFilename==0 ) return 0;
399 in = fopen(zFilename, "rb");
400 if( in==0 ) return 0;
401 fseek(in, 0, SEEK_END);
402 *sz = nIn = ftell(in);
403 rewind(in);
404 pBuf = sqlite3_malloc64( nIn+1 );
405 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
406 pBuf[nIn] = 0;
407 fclose(in);
408 return (char*)pBuf;
410 sqlite3_free(pBuf);
411 *sz = 0;
412 fclose(in);
413 return 0;
418 ** Implementation of the "readfile(X)" SQL function. The entire content
419 ** of the file named X is read and returned as a BLOB. NULL is returned
420 ** if the file does not exist or is unreadable.
422 static void readfileFunc(
423 sqlite3_context *context,
424 int argc,
425 sqlite3_value **argv
427 long nIn;
428 void *pBuf;
429 const char *zName = (const char*)sqlite3_value_text(argv[0]);
431 if( zName==0 ) return;
432 pBuf = readFile(zName, &nIn);
433 if( pBuf ){
434 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
439 ** Implementation of the "readtextfile(X)" SQL function. The text content
440 ** of the file named X through the end of the file or to the first \000
441 ** character, whichever comes first, is read and returned as TEXT. NULL
442 ** is returned if the file does not exist or is unreadable.
444 static void readtextfileFunc(
445 sqlite3_context *context,
446 int argc,
447 sqlite3_value **argv
449 const char *zName;
450 FILE *in;
451 long nIn;
452 char *pBuf;
454 zName = (const char*)sqlite3_value_text(argv[0]);
455 if( zName==0 ) return;
456 in = fopen(zName, "rb");
457 if( in==0 ) return;
458 fseek(in, 0, SEEK_END);
459 nIn = ftell(in);
460 rewind(in);
461 pBuf = sqlite3_malloc64( nIn+1 );
462 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
463 pBuf[nIn] = 0;
464 sqlite3_result_text(context, pBuf, -1, sqlite3_free);
465 }else{
466 sqlite3_free(pBuf);
468 fclose(in);
472 ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
473 ** is written into file X. The number of bytes written is returned. Or
474 ** NULL is returned if something goes wrong, such as being unable to open
475 ** file X for writing.
477 static void writefileFunc(
478 sqlite3_context *context,
479 int argc,
480 sqlite3_value **argv
482 FILE *out;
483 const char *z;
484 sqlite3_int64 rc;
485 const char *zFile;
487 (void)argc;
488 zFile = (const char*)sqlite3_value_text(argv[0]);
489 if( zFile==0 ) return;
490 out = fopen(zFile, "wb");
491 if( out==0 ) return;
492 z = (const char*)sqlite3_value_blob(argv[1]);
493 if( z==0 ){
494 rc = 0;
495 }else{
496 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
498 fclose(out);
499 sqlite3_result_int64(context, rc);
504 ** Load a list of Blob objects from the database
506 static void blobListLoadFromDb(
507 sqlite3 *db, /* Read from this database */
508 const char *zSql, /* Query used to extract the blobs */
509 int onlyId, /* Only load where id is this value */
510 int *pN, /* OUT: Write number of blobs loaded here */
511 Blob **ppList /* OUT: Write the head of the blob list here */
513 Blob head;
514 Blob *p;
515 sqlite3_stmt *pStmt;
516 int n = 0;
517 int rc;
518 char *z2;
520 if( onlyId>0 ){
521 z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
522 }else{
523 z2 = sqlite3_mprintf("%s", zSql);
525 rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
526 sqlite3_free(z2);
527 if( rc ) fatalError("%s", sqlite3_errmsg(db));
528 head.pNext = 0;
529 p = &head;
530 while( SQLITE_ROW==sqlite3_step(pStmt) ){
531 int sz = sqlite3_column_bytes(pStmt, 1);
532 Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
533 pNew->id = sqlite3_column_int(pStmt, 0);
534 pNew->sz = sz;
535 pNew->seq = n++;
536 pNew->pNext = 0;
537 memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
538 pNew->a[sz] = 0;
539 p->pNext = pNew;
540 p = pNew;
542 sqlite3_finalize(pStmt);
543 *pN = n;
544 *ppList = head.pNext;
548 ** Free a list of Blob objects
550 static void blobListFree(Blob *p){
551 Blob *pNext;
552 while( p ){
553 pNext = p->pNext;
554 free(p);
555 p = pNext;
559 /* Return the current wall-clock time
561 ** The number of milliseconds since the julian epoch.
562 ** 1907-01-01 00:00:00 -> 210866716800000
563 ** 2021-01-01 00:00:00 -> 212476176000000
565 static sqlite3_int64 timeOfDay(void){
566 static sqlite3_vfs *clockVfs = 0;
567 sqlite3_int64 t;
568 if( clockVfs==0 ){
569 clockVfs = sqlite3_vfs_find(0);
570 if( clockVfs==0 ) return 0;
572 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
573 clockVfs->xCurrentTimeInt64(clockVfs, &t);
574 }else{
575 double r;
576 clockVfs->xCurrentTime(clockVfs, &r);
577 t = (sqlite3_int64)(r*86400000.0);
579 return t;
582 /***************************************************************************
583 ** Code to process combined database+SQL scripts generated by the
584 ** dbsqlfuzz fuzzer.
587 /* An instance of the following object is passed by pointer as the
588 ** client data to various callbacks.
590 typedef struct FuzzCtx {
591 sqlite3 *db; /* The database connection */
592 sqlite3_int64 iCutoffTime; /* Stop processing at this time. */
593 sqlite3_int64 iLastCb; /* Time recorded for previous progress callback */
594 sqlite3_int64 mxInterval; /* Longest interval between two progress calls */
595 unsigned nCb; /* Number of progress callbacks */
596 unsigned mxCb; /* Maximum number of progress callbacks allowed */
597 unsigned execCnt; /* Number of calls to the sqlite3_exec callback */
598 int timeoutHit; /* True when reaching a timeout */
599 } FuzzCtx;
601 /* Verbosity level for the dbsqlfuzz test runner */
602 static int eVerbosity = 0;
604 /* True to activate PRAGMA vdbe_debug=on */
605 static int bVdbeDebug = 0;
607 /* Timeout for each fuzzing attempt, in milliseconds */
608 static int giTimeout = 10000; /* Defaults to 10 seconds */
610 /* Maximum number of progress handler callbacks */
611 static unsigned int mxProgressCb = 2000;
613 /* Maximum string length in SQLite */
614 static int lengthLimit = 1000000;
616 /* Maximum expression depth */
617 static int depthLimit = 500;
619 /* Limit on the amount of heap memory that can be used */
620 static sqlite3_int64 heapLimit = 100000000;
622 /* Maximum byte-code program length in SQLite */
623 static int vdbeOpLimit = 25000;
625 /* Maximum size of the in-memory database */
626 static sqlite3_int64 maxDbSize = 104857600;
627 /* OOM simulation parameters */
628 static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */
629 static unsigned int oomRepeat = 0; /* Number of OOMs in a row */
630 static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
632 /* Enable recovery */
633 static int bNoRecover = 0;
635 /* This routine is called when a simulated OOM occurs. It is broken
636 ** out as a separate routine to make it easy to set a breakpoint on
637 ** the OOM
639 void oomFault(void){
640 if( eVerbosity ){
641 printf("Simulated OOM fault\n");
643 if( oomRepeat>0 ){
644 oomRepeat--;
645 }else{
646 oomCounter--;
650 /* This routine is a replacement malloc() that is used to simulate
651 ** Out-Of-Memory (OOM) errors for testing purposes.
653 static void *oomMalloc(int nByte){
654 if( oomCounter ){
655 if( oomCounter==1 ){
656 oomFault();
657 return 0;
658 }else{
659 oomCounter--;
662 return defaultMalloc(nByte);
665 /* Register the OOM simulator. This must occur before any memory
666 ** allocations */
667 static void registerOomSimulator(void){
668 sqlite3_mem_methods mem;
669 sqlite3_shutdown();
670 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
671 defaultMalloc = mem.xMalloc;
672 mem.xMalloc = oomMalloc;
673 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
676 /* Turn off any pending OOM simulation */
677 static void disableOom(void){
678 oomCounter = 0;
679 oomRepeat = 0;
683 ** Translate a single byte of Hex into an integer.
684 ** This routine only works if h really is a valid hexadecimal
685 ** character: 0..9a..fA..F
687 static unsigned char hexToInt(unsigned int h){
688 #ifdef SQLITE_EBCDIC
689 h += 9*(1&~(h>>4)); /* EBCDIC */
690 #else
691 h += 9*(1&(h>>6)); /* ASCII */
692 #endif
693 return h & 0xf;
697 ** The first character of buffer zIn[0..nIn-1] is a '['. This routine
698 ** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
699 ** does it makes corresponding changes to the *pK value and *pI value
700 ** and returns true. If the input buffer does not match the patterns,
701 ** no changes are made to either *pK or *pI and this routine returns false.
703 static int isOffset(
704 const unsigned char *zIn, /* Text input */
705 int nIn, /* Bytes of input */
706 unsigned int *pK, /* half-byte cursor to adjust */
707 unsigned int *pI /* Input index to adjust */
709 int i;
710 unsigned int k = 0;
711 unsigned char c;
712 for(i=1; i<nIn && (c = zIn[i])!=']'; i++){
713 if( !isxdigit(c) ) return 0;
714 k = k*16 + hexToInt(c);
716 if( i==nIn ) return 0;
717 *pK = 2*k;
718 *pI += i;
719 return 1;
723 ** Decode the text starting at zIn into a binary database file.
724 ** The maximum length of zIn is nIn bytes. Store the binary database
725 ** file in space obtained from sqlite3_malloc().
727 ** Return the number of bytes of zIn consumed. Or return -1 if there
728 ** is an error. One potential error is that the recipe specifies a
729 ** database file larger than MX_FILE_SZ bytes.
731 ** Abort on an OOM.
733 static int decodeDatabase(
734 const unsigned char *zIn, /* Input text to be decoded */
735 int nIn, /* Bytes of input text */
736 unsigned char **paDecode, /* OUT: decoded database file */
737 int *pnDecode /* OUT: Size of decoded database */
739 unsigned char *a, *aNew; /* Database under construction */
740 int mx = 0; /* Current size of the database */
741 sqlite3_uint64 nAlloc = 4096; /* Space allocated in a[] */
742 unsigned int i; /* Next byte of zIn[] to read */
743 unsigned int j; /* Temporary integer */
744 unsigned int k; /* half-byte cursor index for output */
745 unsigned int n; /* Number of bytes of input */
746 unsigned char b = 0;
747 if( nIn<4 ) return -1;
748 n = (unsigned int)nIn;
749 a = sqlite3_malloc64( nAlloc );
750 if( a==0 ){
751 fprintf(stderr, "Out of memory!\n");
752 exit(1);
754 memset(a, 0, (size_t)nAlloc);
755 for(i=k=0; i<n; i++){
756 unsigned char c = (unsigned char)zIn[i];
757 if( isxdigit(c) ){
758 k++;
759 if( k & 1 ){
760 b = hexToInt(c)*16;
761 }else{
762 b += hexToInt(c);
763 j = k/2 - 1;
764 if( j>=nAlloc ){
765 sqlite3_uint64 newSize;
766 if( nAlloc==MX_FILE_SZ || j>=MX_FILE_SZ ){
767 if( eVerbosity ){
768 fprintf(stderr, "Input database too big: max %d bytes\n",
769 MX_FILE_SZ);
771 sqlite3_free(a);
772 return -1;
774 newSize = nAlloc*2;
775 if( newSize<=j ){
776 newSize = (j+4096)&~4095;
778 if( newSize>MX_FILE_SZ ){
779 if( j>=MX_FILE_SZ ){
780 sqlite3_free(a);
781 return -1;
783 newSize = MX_FILE_SZ;
785 aNew = sqlite3_realloc64( a, newSize );
786 if( aNew==0 ){
787 sqlite3_free(a);
788 return -1;
790 a = aNew;
791 assert( newSize > nAlloc );
792 memset(a+nAlloc, 0, (size_t)(newSize - nAlloc));
793 nAlloc = newSize;
795 if( j>=(unsigned)mx ){
796 mx = (j + 4095)&~4095;
797 if( mx>MX_FILE_SZ ) mx = MX_FILE_SZ;
799 assert( j<nAlloc );
800 a[j] = b;
802 }else if( zIn[i]=='[' && i<n-3 && isOffset(zIn+i, nIn-i, &k, &i) ){
803 continue;
804 }else if( zIn[i]=='\n' && i<n-4 && memcmp(zIn+i,"\n--\n",4)==0 ){
805 i += 4;
806 break;
809 *pnDecode = mx;
810 *paDecode = a;
811 return i;
815 ** Progress handler callback.
817 ** The argument is the cutoff-time after which all processing should
818 ** stop. So return non-zero if the cut-off time is exceeded.
820 static int progress_handler(void *pClientData) {
821 FuzzCtx *p = (FuzzCtx*)pClientData;
822 sqlite3_int64 iNow = timeOfDay();
823 int rc = iNow>=p->iCutoffTime;
824 sqlite3_int64 iDiff = iNow - p->iLastCb;
825 /* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */
826 if( iDiff > p->mxInterval ) p->mxInterval = iDiff;
827 p->nCb++;
828 if( rc==0 && p->mxCb>0 && p->mxCb<=p->nCb ) rc = 1;
829 if( rc && !p->timeoutHit && eVerbosity>=2 ){
830 printf("Timeout on progress callback %d\n", p->nCb);
831 fflush(stdout);
832 p->timeoutHit = 1;
834 return rc;
838 ** Flag bits set by block_troublesome_sql()
840 #define BTS_SELECT 0x000001
841 #define BTS_NONSELECT 0x000002
842 #define BTS_BADFUNC 0x000004
843 #define BTS_BADPRAGMA 0x000008 /* Sticky for rest of the script */
846 ** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
847 ** "PRAGMA parser_trace" since they can dramatically increase the
848 ** amount of output without actually testing anything useful.
850 ** Also block ATTACH if attaching a file from the filesystem.
852 static int block_troublesome_sql(
853 void *pClientData,
854 int eCode,
855 const char *zArg1,
856 const char *zArg2,
857 const char *zArg3,
858 const char *zArg4
860 unsigned int *pBtsFlags = (unsigned int*)pClientData;
862 (void)zArg3;
863 (void)zArg4;
864 switch( eCode ){
865 case SQLITE_PRAGMA: {
866 if( sqlite3_stricmp("busy_timeout",zArg1)==0
867 && (zArg2==0 || strtoll(zArg2,0,0)>100 || strtoll(zArg2,0,10)>100)
869 return SQLITE_DENY;
870 }else if( sqlite3_stricmp("hard_heap_limit", zArg1)==0
871 || sqlite3_stricmp("reverse_unordered_selects", zArg1)==0
873 /* BTS_BADPRAGMA is sticky. A hard_heap_limit or
874 ** revert_unordered_selects should inhibit all future attempts
875 ** at verifying query invariants */
876 *pBtsFlags |= BTS_BADPRAGMA;
877 }else if( eVerbosity==0 ){
878 if( sqlite3_strnicmp("vdbe_", zArg1, 5)==0
879 || sqlite3_stricmp("parser_trace", zArg1)==0
880 || sqlite3_stricmp("temp_store_directory", zArg1)==0
882 return SQLITE_DENY;
884 }else if( sqlite3_stricmp("oom",zArg1)==0
885 && zArg2!=0 && zArg2[0]!=0 ){
886 oomCounter = atoi(zArg2);
888 *pBtsFlags |= BTS_NONSELECT;
889 break;
891 case SQLITE_ATTACH: {
892 /* Deny the ATTACH if it is attaching anything other than an in-memory
893 ** database. */
894 *pBtsFlags |= BTS_NONSELECT;
895 if( zArg1==0 ) return SQLITE_DENY;
896 if( strcmp(zArg1,":memory:")==0 ) return SQLITE_OK;
897 if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1)==0
898 && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1)!=0
900 return SQLITE_OK;
902 return SQLITE_DENY;
904 case SQLITE_SELECT: {
905 *pBtsFlags |= BTS_SELECT;
906 break;
908 case SQLITE_FUNCTION: {
909 static const char *azBadFuncs[] = {
910 "avg",
911 "count",
912 "cume_dist",
913 "current_date",
914 "current_time",
915 "current_timestamp",
916 "date",
917 "datetime",
918 "decimal_sum",
919 "dense_rank",
920 "first_value",
921 "geopoly_group_bbox",
922 "group_concat",
923 "implies_nonnull_row",
924 "json_group_array",
925 "json_group_object",
926 "julianday",
927 "lag",
928 "last_value",
929 "lead",
930 "max",
931 "min",
932 "nth_value",
933 "ntile",
934 "percent_rank",
935 "random",
936 "randomblob",
937 "rank",
938 "row_number",
939 "sqlite_offset",
940 "strftime",
941 "sum",
942 "time",
943 "total",
944 "unixepoch",
946 int first, last;
947 first = 0;
948 last = sizeof(azBadFuncs)/sizeof(azBadFuncs[0]) - 1;
950 int mid = (first+last)/2;
951 int c = sqlite3_stricmp(azBadFuncs[mid], zArg2);
952 if( c<0 ){
953 first = mid+1;
954 }else if( c>0 ){
955 last = mid-1;
956 }else{
957 *pBtsFlags |= BTS_BADFUNC;
958 break;
960 }while( first<=last );
961 break;
963 case SQLITE_READ: {
964 /* Benign */
965 break;
967 default: {
968 *pBtsFlags |= BTS_NONSELECT;
971 return SQLITE_OK;
974 /* Implementation found in fuzzinvariant.c */
975 extern int fuzz_invariant(
976 sqlite3 *db, /* The database connection */
977 sqlite3_stmt *pStmt, /* Test statement stopped on an SQLITE_ROW */
978 int iCnt, /* Invariant sequence number, starting at 0 */
979 int iRow, /* The row number for pStmt */
980 int nRow, /* Total number of output rows */
981 int *pbCorrupt, /* IN/OUT: Flag indicating a corrupt database file */
982 int eVerbosity, /* How much debugging output */
983 unsigned int dbOpt /* Default optimization flags */
986 /* Implementation of sqlite_dbdata and sqlite_dbptr */
987 extern int sqlite3_dbdata_init(sqlite3*,const char**,void*);
991 ** This function is used as a callback by the recover extension. Simply
992 ** print the supplied SQL statement to stdout.
994 static int recoverSqlCb(void *pCtx, const char *zSql){
995 if( eVerbosity>=2 ){
996 printf("%s\n", zSql);
998 return SQLITE_OK;
1002 ** This function is called to recover data from the database.
1004 static int recoverDatabase(sqlite3 *db){
1005 int rc; /* Return code from this routine */
1006 const char *zRecoveryDb = ""; /* Name of "recovery" database */
1007 const char *zLAF = "lost_and_found"; /* Name of "lost_and_found" table */
1008 int bFreelist = 1; /* True to scan the freelist */
1009 int bRowids = 1; /* True to restore ROWID values */
1010 sqlite3_recover *p = 0; /* The recovery object */
1012 p = sqlite3_recover_init_sql(db, "main", recoverSqlCb, 0);
1013 sqlite3_recover_config(p, 789, (void*)zRecoveryDb);
1014 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
1015 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
1016 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
1017 sqlite3_recover_run(p);
1018 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
1019 const char *zErr = sqlite3_recover_errmsg(p);
1020 int errCode = sqlite3_recover_errcode(p);
1021 if( eVerbosity>0 ){
1022 printf("recovery error: %s (%d)\n", zErr, errCode);
1025 rc = sqlite3_recover_finish(p);
1026 if( eVerbosity>0 && rc ){
1027 printf("recovery returns error code %d\n", rc);
1029 return rc;
1033 ** Run the SQL text
1035 static int runDbSql(
1036 sqlite3 *db, /* Run SQL on this database connection */
1037 const char *zSql, /* The SQL to be run */
1038 unsigned int *pBtsFlags,
1039 unsigned int dbOpt /* Default optimization flags */
1041 int rc;
1042 sqlite3_stmt *pStmt;
1043 int bCorrupt = 0;
1044 while( isspace(zSql[0]&0x7f) ) zSql++;
1045 if( zSql[0]==0 ) return SQLITE_OK;
1046 if( eVerbosity>=4 ){
1047 printf("RUNNING-SQL: [%s]\n", zSql);
1048 fflush(stdout);
1050 (*pBtsFlags) &= BTS_BADPRAGMA;
1051 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
1052 if( rc==SQLITE_OK ){
1053 int nRow = 0;
1054 while( (rc = sqlite3_step(pStmt))==SQLITE_ROW ){
1055 nRow++;
1056 if( eVerbosity>=4 ){
1057 int j;
1058 for(j=0; j<sqlite3_column_count(pStmt); j++){
1059 if( j ) printf(",");
1060 switch( sqlite3_column_type(pStmt, j) ){
1061 case SQLITE_NULL: {
1062 printf("NULL");
1063 break;
1065 case SQLITE_INTEGER:
1066 case SQLITE_FLOAT: {
1067 printf("%s", sqlite3_column_text(pStmt, j));
1068 break;
1070 case SQLITE_BLOB: {
1071 int n = sqlite3_column_bytes(pStmt, j);
1072 int i;
1073 const unsigned char *a;
1074 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
1075 printf("x'");
1076 for(i=0; i<n; i++){
1077 printf("%02x", a[i]);
1079 printf("'");
1080 break;
1082 case SQLITE_TEXT: {
1083 int n = sqlite3_column_bytes(pStmt, j);
1084 int i;
1085 const unsigned char *a;
1086 a = (const unsigned char*)sqlite3_column_blob(pStmt, j);
1087 printf("'");
1088 for(i=0; i<n; i++){
1089 if( a[i]=='\'' ){
1090 printf("''");
1091 }else{
1092 putchar(a[i]);
1095 printf("'");
1096 break;
1098 } /* End switch() */
1099 } /* End for() */
1100 printf("\n");
1101 fflush(stdout);
1102 } /* End if( eVerbosity>=5 ) */
1103 } /* End while( SQLITE_ROW */
1104 if( rc==SQLITE_DONE ){
1105 if( (*pBtsFlags)==BTS_SELECT
1106 && !sqlite3_stmt_isexplain(pStmt)
1107 && nRow>0
1109 int iRow = 0;
1110 sqlite3_reset(pStmt);
1111 while( sqlite3_step(pStmt)==SQLITE_ROW ){
1112 int iCnt = 0;
1113 iRow++;
1114 for(iCnt=0; iCnt<99999; iCnt++){
1115 rc = fuzz_invariant(db, pStmt, iCnt, iRow, nRow,
1116 &bCorrupt, eVerbosity, dbOpt);
1117 if( rc==SQLITE_DONE ) break;
1118 if( rc!=SQLITE_ERROR ) g.nInvariant++;
1119 if( eVerbosity>0 ){
1120 if( rc==SQLITE_OK ){
1121 printf("invariant-check: ok\n");
1122 }else if( rc==SQLITE_CORRUPT ){
1123 printf("invariant-check: failed due to database corruption\n");
1129 }else if( eVerbosity>=4 ){
1130 printf("SQL-ERROR: (%d) %s\n", rc, sqlite3_errmsg(db));
1131 fflush(stdout);
1133 }else if( eVerbosity>=4 ){
1134 printf("SQL-ERROR (%d): %s\n", rc, sqlite3_errmsg(db));
1135 fflush(stdout);
1136 } /* End if( SQLITE_OK ) */
1137 return sqlite3_finalize(pStmt);
1140 /* Mappings into dbconfig settings for bits taken from bytes 72..75 of
1141 ** the input database.
1143 ** This should be the same as in dbsqlfuzz.c. Make sure those codes stay
1144 ** in sync.
1146 static const struct {
1147 unsigned int mask;
1148 int iSetting;
1149 char *zName;
1150 } aDbConfigSettings[] = {
1151 { 0x0001, SQLITE_DBCONFIG_ENABLE_FKEY, "enable_fkey" },
1152 { 0x0002, SQLITE_DBCONFIG_ENABLE_TRIGGER, "enable_trigger" },
1153 { 0x0004, SQLITE_DBCONFIG_ENABLE_VIEW, "enable_view" },
1154 { 0x0008, SQLITE_DBCONFIG_ENABLE_QPSG, "enable_qpsg" },
1155 { 0x0010, SQLITE_DBCONFIG_TRIGGER_EQP, "trigger_eqp" },
1156 { 0x0020, SQLITE_DBCONFIG_DEFENSIVE, "defensive" },
1157 { 0x0040, SQLITE_DBCONFIG_WRITABLE_SCHEMA, "writable_schema" },
1158 { 0x0080, SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, "legacy_alter_table" },
1159 { 0x0100, SQLITE_DBCONFIG_STMT_SCANSTATUS, "stmt_scanstatus" },
1160 { 0x0200, SQLITE_DBCONFIG_REVERSE_SCANORDER, "reverse_scanorder" },
1161 #ifdef SQLITE_DBCONFIG_STRICT_AGGREGATE
1162 { 0x0400, SQLITE_DBCONFIG_STRICT_AGGREGATE, "strict_aggregate" },
1163 #endif
1164 { 0x0800, SQLITE_DBCONFIG_DQS_DML, "dqs_dml" },
1165 { 0x1000, SQLITE_DBCONFIG_DQS_DDL, "dqs_ddl" },
1166 { 0x2000, SQLITE_DBCONFIG_TRUSTED_SCHEMA, "trusted_schema" },
1169 /* Toggle a dbconfig setting
1171 static void toggleDbConfig(sqlite3 *db, int iSetting){
1172 int v = 0;
1173 sqlite3_db_config(db, iSetting, -1, &v);
1174 v = !v;
1175 sqlite3_db_config(db, iSetting, v, 0);
1178 /* Invoke this routine to run a single test case */
1179 int runCombinedDbSqlInput(
1180 const uint8_t *aData, /* Combined DB+SQL content */
1181 size_t nByte, /* Size of aData in bytes */
1182 int iTimeout, /* Use this timeout */
1183 int bScript, /* If true, just render CLI output */
1184 int iSqlId /* SQL identifier */
1186 int rc; /* SQLite API return value */
1187 int iSql; /* Index in aData[] of start of SQL */
1188 unsigned char *aDb = 0; /* Decoded database content */
1189 int nDb = 0; /* Size of the decoded database */
1190 int i; /* Loop counter */
1191 int j; /* Start of current SQL statement */
1192 char *zSql = 0; /* SQL text to run */
1193 int nSql; /* Bytes of SQL text */
1194 FuzzCtx cx; /* Fuzzing context */
1195 unsigned int btsFlags = 0; /* Parsing flags */
1196 unsigned int dbFlags = 0; /* Flag values from db offset 72..75 */
1197 unsigned int dbOpt = 0; /* Flag values from db offset 76..79 */
1200 if( nByte<10 ) return 0;
1201 if( sqlite3_initialize() ) return 0;
1202 if( sqlite3_memory_used()!=0 ){
1203 int nAlloc = 0;
1204 int nNotUsed = 0;
1205 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1206 fprintf(stderr,"memory leak prior to test start:"
1207 " %lld bytes in %d allocations\n",
1208 sqlite3_memory_used(), nAlloc);
1209 exit(1);
1211 memset(&cx, 0, sizeof(cx));
1212 iSql = decodeDatabase((unsigned char*)aData, (int)nByte, &aDb, &nDb);
1213 if( iSql<0 ) return 0;
1214 if( nDb>=75 ){
1215 dbFlags = ((unsigned int)aDb[72]<<24) + ((unsigned int)aDb[73]<<16) +
1216 ((unsigned int)aDb[74]<<8) + (unsigned int)aDb[75];
1218 if( nDb>=79 ){
1219 dbOpt = ((unsigned int)aDb[76]<<24) + ((unsigned int)aDb[77]<<16) +
1220 ((unsigned int)aDb[78]<<8) + (unsigned int)aDb[79];
1222 nSql = (int)(nByte - iSql);
1223 if( bScript ){
1224 char zName[100];
1225 sqlite3_snprintf(sizeof(zName),zName,"dbsql%06d.db",iSqlId);
1226 renderDbSqlForCLI(stdout, zName, aDb, nDb,
1227 (unsigned char*)(aData+iSql), nSql);
1228 sqlite3_free(aDb);
1229 return 0;
1231 if( eVerbosity>=3 ){
1232 printf(
1233 "****** %d-byte input, %d-byte database, %d-byte script "
1234 "******\n", (int)nByte, nDb, nSql);
1235 fflush(stdout);
1237 rc = sqlite3_open(0, &cx.db);
1238 if( rc ){
1239 sqlite3_free(aDb);
1240 return 1;
1242 sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, cx.db, dbOpt);
1243 for(i=0; i<sizeof(aDbConfigSettings)/sizeof(aDbConfigSettings[0]); i++){
1244 if( dbFlags & aDbConfigSettings[i].mask ){
1245 toggleDbConfig(cx.db, aDbConfigSettings[i].iSetting);
1248 if( bVdbeDebug ){
1249 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
1252 /* Invoke the progress handler frequently to check to see if we
1253 ** are taking too long. The progress handler will return true
1254 ** (which will block further processing) if more than giTimeout seconds have
1255 ** elapsed since the start of the test.
1257 cx.iLastCb = timeOfDay();
1258 cx.iCutoffTime = cx.iLastCb + (iTimeout<giTimeout ? iTimeout : giTimeout);
1259 cx.mxCb = mxProgressCb;
1260 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1261 sqlite3_progress_handler(cx.db, 10, progress_handler, (void*)&cx);
1262 #endif
1264 /* Set a limit on the maximum size of a prepared statement, and the
1265 ** maximum length of a string or blob */
1266 if( vdbeOpLimit>0 ){
1267 sqlite3_limit(cx.db, SQLITE_LIMIT_VDBE_OP, vdbeOpLimit);
1269 if( lengthLimit>0 ){
1270 sqlite3_limit(cx.db, SQLITE_LIMIT_LENGTH, lengthLimit);
1272 if( depthLimit>0 ){
1273 sqlite3_limit(cx.db, SQLITE_LIMIT_EXPR_DEPTH, depthLimit);
1275 sqlite3_limit(cx.db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 100);
1276 sqlite3_hard_heap_limit64(heapLimit);
1277 rc = 1;
1278 sqlite3_test_control(SQLITE_TESTCTRL_JSON_SELFCHECK, &rc);
1280 if( nDb>=20 && aDb[18]==2 && aDb[19]==2 ){
1281 aDb[18] = aDb[19] = 1;
1283 rc = sqlite3_deserialize(cx.db, "main", aDb, nDb, nDb,
1284 SQLITE_DESERIALIZE_RESIZEABLE |
1285 SQLITE_DESERIALIZE_FREEONCLOSE);
1286 if( rc ){
1287 fprintf(stderr, "sqlite3_deserialize() failed with %d\n", rc);
1288 goto testrun_finished;
1290 if( maxDbSize>0 ){
1291 sqlite3_int64 x = maxDbSize;
1292 sqlite3_file_control(cx.db, "main", SQLITE_FCNTL_SIZE_LIMIT, &x);
1295 /* For high debugging levels, turn on debug mode */
1296 if( eVerbosity>=5 ){
1297 sqlite3_exec(cx.db, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
1300 /* Block debug pragmas and ATTACH/DETACH. But wait until after
1301 ** deserialize to do this because deserialize depends on ATTACH */
1302 sqlite3_set_authorizer(cx.db, block_troublesome_sql, &btsFlags);
1304 /* Add the vt02 virtual table */
1305 sqlite3_vt02_init(cx.db, 0, 0);
1307 /* Add the random_json() and random_json5() functions */
1308 sqlite3_randomjson_init(cx.db, 0, 0);
1310 /* Add support for sqlite_dbdata and sqlite_dbptr virtual tables used
1311 ** by the recovery API */
1312 sqlite3_dbdata_init(cx.db, 0, 0);
1314 /* Consistent PRNG seed */
1315 #ifdef SQLITE_TESTCTRL_PRNG_SEED
1316 sqlite3_table_column_metadata(cx.db, 0, "x", 0, 0, 0, 0, 0, 0);
1317 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, cx.db);
1318 #else
1319 sqlite3_randomness(0,0);
1320 #endif
1322 /* Run recovery on the initial database, just to make sure recovery
1323 ** works. */
1324 if( !bNoRecover ){
1325 recoverDatabase(cx.db);
1328 zSql = sqlite3_malloc( nSql + 1 );
1329 if( zSql==0 ){
1330 fprintf(stderr, "Out of memory!\n");
1331 }else{
1332 memcpy(zSql, aData+iSql, nSql);
1333 zSql[nSql] = 0;
1334 for(i=j=0; zSql[i]; i++){
1335 if( zSql[i]==';' ){
1336 char cSaved = zSql[i+1];
1337 zSql[i+1] = 0;
1338 if( sqlite3_complete(zSql+j) ){
1339 rc = runDbSql(cx.db, zSql+j, &btsFlags, dbOpt);
1340 j = i+1;
1342 zSql[i+1] = cSaved;
1343 if( rc==SQLITE_INTERRUPT || progress_handler(&cx) ){
1344 goto testrun_finished;
1348 if( j<i ){
1349 runDbSql(cx.db, zSql+j, &btsFlags, dbOpt);
1352 testrun_finished:
1353 sqlite3_free(zSql);
1354 rc = sqlite3_close(cx.db);
1355 if( rc!=SQLITE_OK ){
1356 fprintf(stdout, "sqlite3_close() returns %d\n", rc);
1358 if( eVerbosity>=2 && !bScript ){
1359 fprintf(stdout, "Peak memory usages: %f MB\n",
1360 sqlite3_memory_highwater(1) / 1000000.0);
1362 if( sqlite3_memory_used()!=0 ){
1363 int nAlloc = 0;
1364 int nNotUsed = 0;
1365 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &nAlloc, &nNotUsed, 0);
1366 fprintf(stderr,"Memory leak: %lld bytes in %d allocations\n",
1367 sqlite3_memory_used(), nAlloc);
1368 exit(1);
1370 sqlite3_hard_heap_limit64(0);
1371 sqlite3_soft_heap_limit64(0);
1372 return 0;
1376 ** END of the dbsqlfuzz code
1377 ***************************************************************************/
1379 /* Look at a SQL text and try to determine if it begins with a database
1380 ** description, such as would be found in a dbsqlfuzz test case. Return
1381 ** true if this does appear to be a dbsqlfuzz test case and false otherwise.
1383 static int isDbSql(unsigned char *a, int n){
1384 unsigned char buf[12];
1385 int i;
1386 if( n>4 && memcmp(a,"\n--\n",4)==0 ) return 1;
1387 while( n>0 && isspace(a[0]) ){ a++; n--; }
1388 for(i=0; n>0 && i<8; n--, a++){
1389 if( isxdigit(a[0]) ) buf[i++] = a[0];
1391 if( i==8 && memcmp(buf,"53514c69",8)==0 ) return 1;
1392 return 0;
1395 /* Implementation of the isdbsql(TEXT) SQL function.
1397 static void isDbSqlFunc(
1398 sqlite3_context *context,
1399 int argc,
1400 sqlite3_value **argv
1402 int n = sqlite3_value_bytes(argv[0]);
1403 unsigned char *a = (unsigned char*)sqlite3_value_blob(argv[0]);
1404 sqlite3_result_int(context, a!=0 && n>0 && isDbSql(a,n));
1407 /* Methods for the VHandle object
1409 static int inmemClose(sqlite3_file *pFile){
1410 VHandle *p = (VHandle*)pFile;
1411 VFile *pVFile = p->pVFile;
1412 pVFile->nRef--;
1413 if( pVFile->nRef==0 && pVFile->zFilename==0 ){
1414 pVFile->sz = -1;
1415 free(pVFile->a);
1416 pVFile->a = 0;
1418 return SQLITE_OK;
1420 static int inmemRead(
1421 sqlite3_file *pFile, /* Read from this open file */
1422 void *pData, /* Store content in this buffer */
1423 int iAmt, /* Bytes of content */
1424 sqlite3_int64 iOfst /* Start reading here */
1426 VHandle *pHandle = (VHandle*)pFile;
1427 VFile *pVFile = pHandle->pVFile;
1428 if( iOfst<0 || iOfst>=pVFile->sz ){
1429 memset(pData, 0, iAmt);
1430 return SQLITE_IOERR_SHORT_READ;
1432 if( iOfst+iAmt>pVFile->sz ){
1433 memset(pData, 0, iAmt);
1434 iAmt = (int)(pVFile->sz - iOfst);
1435 memcpy(pData, pVFile->a + iOfst, iAmt);
1436 return SQLITE_IOERR_SHORT_READ;
1438 memcpy(pData, pVFile->a + iOfst, iAmt);
1439 return SQLITE_OK;
1441 static int inmemWrite(
1442 sqlite3_file *pFile, /* Write to this file */
1443 const void *pData, /* Content to write */
1444 int iAmt, /* bytes to write */
1445 sqlite3_int64 iOfst /* Start writing here */
1447 VHandle *pHandle = (VHandle*)pFile;
1448 VFile *pVFile = pHandle->pVFile;
1449 if( iOfst+iAmt > pVFile->sz ){
1450 if( iOfst+iAmt >= MX_FILE_SZ ){
1451 return SQLITE_FULL;
1453 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
1454 if( iOfst > pVFile->sz ){
1455 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
1457 pVFile->sz = (int)(iOfst + iAmt);
1459 memcpy(pVFile->a + iOfst, pData, iAmt);
1460 return SQLITE_OK;
1462 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
1463 VHandle *pHandle = (VHandle*)pFile;
1464 VFile *pVFile = pHandle->pVFile;
1465 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
1466 return SQLITE_OK;
1468 static int inmemSync(sqlite3_file *pFile, int flags){
1469 return SQLITE_OK;
1471 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
1472 *pSize = ((VHandle*)pFile)->pVFile->sz;
1473 return SQLITE_OK;
1475 static int inmemLock(sqlite3_file *pFile, int type){
1476 return SQLITE_OK;
1478 static int inmemUnlock(sqlite3_file *pFile, int type){
1479 return SQLITE_OK;
1481 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
1482 *pOut = 0;
1483 return SQLITE_OK;
1485 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
1486 return SQLITE_NOTFOUND;
1488 static int inmemSectorSize(sqlite3_file *pFile){
1489 return 512;
1491 static int inmemDeviceCharacteristics(sqlite3_file *pFile){
1492 return
1493 SQLITE_IOCAP_SAFE_APPEND |
1494 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
1495 SQLITE_IOCAP_POWERSAFE_OVERWRITE;
1499 /* Method table for VHandle
1501 static sqlite3_io_methods VHandleMethods = {
1502 /* iVersion */ 1,
1503 /* xClose */ inmemClose,
1504 /* xRead */ inmemRead,
1505 /* xWrite */ inmemWrite,
1506 /* xTruncate */ inmemTruncate,
1507 /* xSync */ inmemSync,
1508 /* xFileSize */ inmemFileSize,
1509 /* xLock */ inmemLock,
1510 /* xUnlock */ inmemUnlock,
1511 /* xCheck... */ inmemCheckReservedLock,
1512 /* xFileCtrl */ inmemFileControl,
1513 /* xSectorSz */ inmemSectorSize,
1514 /* xDevchar */ inmemDeviceCharacteristics,
1515 /* xShmMap */ 0,
1516 /* xShmLock */ 0,
1517 /* xShmBarrier */ 0,
1518 /* xShmUnmap */ 0,
1519 /* xFetch */ 0,
1520 /* xUnfetch */ 0
1524 ** Open a new file in the inmem VFS. All files are anonymous and are
1525 ** delete-on-close.
1527 static int inmemOpen(
1528 sqlite3_vfs *pVfs,
1529 const char *zFilename,
1530 sqlite3_file *pFile,
1531 int openFlags,
1532 int *pOutFlags
1534 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
1535 VHandle *pHandle = (VHandle*)pFile;
1536 if( pVFile==0 ){
1537 return SQLITE_FULL;
1539 pHandle->pVFile = pVFile;
1540 pVFile->nRef++;
1541 pFile->pMethods = &VHandleMethods;
1542 if( pOutFlags ) *pOutFlags = openFlags;
1543 return SQLITE_OK;
1547 ** Delete a file by name
1549 static int inmemDelete(
1550 sqlite3_vfs *pVfs,
1551 const char *zFilename,
1552 int syncdir
1554 VFile *pVFile = findVFile(zFilename);
1555 if( pVFile==0 ) return SQLITE_OK;
1556 if( pVFile->nRef==0 ){
1557 free(pVFile->zFilename);
1558 pVFile->zFilename = 0;
1559 pVFile->sz = -1;
1560 free(pVFile->a);
1561 pVFile->a = 0;
1562 return SQLITE_OK;
1564 return SQLITE_IOERR_DELETE;
1567 /* Check for the existance of a file
1569 static int inmemAccess(
1570 sqlite3_vfs *pVfs,
1571 const char *zFilename,
1572 int flags,
1573 int *pResOut
1575 VFile *pVFile = findVFile(zFilename);
1576 *pResOut = pVFile!=0;
1577 return SQLITE_OK;
1580 /* Get the canonical pathname for a file
1582 static int inmemFullPathname(
1583 sqlite3_vfs *pVfs,
1584 const char *zFilename,
1585 int nOut,
1586 char *zOut
1588 sqlite3_snprintf(nOut, zOut, "%s", zFilename);
1589 return SQLITE_OK;
1592 /* Always use the same random see, for repeatability.
1594 static int inmemRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
1595 memset(zBuf, 0, nBuf);
1596 memcpy(zBuf, &g.uRandom, nBuf<sizeof(g.uRandom) ? nBuf : sizeof(g.uRandom));
1597 return nBuf;
1601 ** Register the VFS that reads from the g.aFile[] set of files.
1603 static void inmemVfsRegister(int makeDefault){
1604 static sqlite3_vfs inmemVfs;
1605 sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
1606 inmemVfs.iVersion = 3;
1607 inmemVfs.szOsFile = sizeof(VHandle);
1608 inmemVfs.mxPathname = 200;
1609 inmemVfs.zName = "inmem";
1610 inmemVfs.xOpen = inmemOpen;
1611 inmemVfs.xDelete = inmemDelete;
1612 inmemVfs.xAccess = inmemAccess;
1613 inmemVfs.xFullPathname = inmemFullPathname;
1614 inmemVfs.xRandomness = inmemRandomness;
1615 inmemVfs.xSleep = pDefault->xSleep;
1616 inmemVfs.xCurrentTimeInt64 = pDefault->xCurrentTimeInt64;
1617 sqlite3_vfs_register(&inmemVfs, makeDefault);
1621 ** Allowed values for the runFlags parameter to runSql()
1623 #define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */
1624 #define SQL_OUTPUT 0x0002 /* Show the SQL output */
1627 ** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not
1628 ** stop if an error is encountered.
1630 static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){
1631 const char *zMore;
1632 sqlite3_stmt *pStmt;
1634 while( zSql && zSql[0] ){
1635 zMore = 0;
1636 pStmt = 0;
1637 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
1638 if( zMore==zSql ) break;
1639 if( runFlags & SQL_TRACE ){
1640 const char *z = zSql;
1641 int n;
1642 while( z<zMore && ISSPACE(z[0]) ) z++;
1643 n = (int)(zMore - z);
1644 while( n>0 && ISSPACE(z[n-1]) ) n--;
1645 if( n==0 ) break;
1646 if( pStmt==0 ){
1647 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
1648 }else{
1649 printf("TRACE: %.*s\n", n, z);
1652 zSql = zMore;
1653 if( pStmt ){
1654 if( (runFlags & SQL_OUTPUT)==0 ){
1655 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
1656 }else{
1657 int nCol = -1;
1658 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1659 int i;
1660 if( nCol<0 ){
1661 nCol = sqlite3_column_count(pStmt);
1662 }else if( nCol>0 ){
1663 printf("--------------------------------------------\n");
1665 for(i=0; i<nCol; i++){
1666 int eType = sqlite3_column_type(pStmt,i);
1667 printf("%s = ", sqlite3_column_name(pStmt,i));
1668 switch( eType ){
1669 case SQLITE_NULL: {
1670 printf("NULL\n");
1671 break;
1673 case SQLITE_INTEGER: {
1674 printf("INT %s\n", sqlite3_column_text(pStmt,i));
1675 break;
1677 case SQLITE_FLOAT: {
1678 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
1679 break;
1681 case SQLITE_TEXT: {
1682 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
1683 break;
1685 case SQLITE_BLOB: {
1686 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
1687 break;
1693 sqlite3_finalize(pStmt);
1699 ** Rebuild the database file.
1701 ** (1) Remove duplicate entries
1702 ** (2) Put all entries in order
1703 ** (3) Vacuum
1705 static void rebuild_database(sqlite3 *db, int dbSqlOnly){
1706 int rc;
1707 char *zSql;
1708 zSql = sqlite3_mprintf(
1709 "BEGIN;\n"
1710 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1711 "DELETE FROM db;\n"
1712 "INSERT INTO db(dbid, dbcontent) "
1713 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
1714 "DROP TABLE dbx;\n"
1715 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
1716 "DELETE FROM xsql;\n"
1717 "INSERT INTO xsql(sqlid,sqltext) "
1718 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
1719 "DROP TABLE sx;\n"
1720 "COMMIT;\n"
1721 "PRAGMA page_size=1024;\n"
1722 "VACUUM;\n",
1723 dbSqlOnly ? " WHERE isdbsql(sqltext)" : ""
1725 rc = sqlite3_exec(db, zSql, 0, 0, 0);
1726 sqlite3_free(zSql);
1727 if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
1731 ** Return the value of a hexadecimal digit. Return -1 if the input
1732 ** is not a hex digit.
1734 static int hexDigitValue(char c){
1735 if( c>='0' && c<='9' ) return c - '0';
1736 if( c>='a' && c<='f' ) return c - 'a' + 10;
1737 if( c>='A' && c<='F' ) return c - 'A' + 10;
1738 return -1;
1742 ** Interpret zArg as an integer value, possibly with suffixes.
1744 static int integerValue(const char *zArg){
1745 sqlite3_int64 v = 0;
1746 static const struct { char *zSuffix; int iMult; } aMult[] = {
1747 { "KiB", 1024 },
1748 { "MiB", 1024*1024 },
1749 { "GiB", 1024*1024*1024 },
1750 { "KB", 1000 },
1751 { "MB", 1000000 },
1752 { "GB", 1000000000 },
1753 { "K", 1000 },
1754 { "M", 1000000 },
1755 { "G", 1000000000 },
1757 int i;
1758 int isNeg = 0;
1759 if( zArg[0]=='-' ){
1760 isNeg = 1;
1761 zArg++;
1762 }else if( zArg[0]=='+' ){
1763 zArg++;
1765 if( zArg[0]=='0' && zArg[1]=='x' ){
1766 int x;
1767 zArg += 2;
1768 while( (x = hexDigitValue(zArg[0]))>=0 ){
1769 v = (v<<4) + x;
1770 zArg++;
1772 }else{
1773 while( ISDIGIT(zArg[0]) ){
1774 v = v*10 + zArg[0] - '0';
1775 zArg++;
1778 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1779 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1780 v *= aMult[i].iMult;
1781 break;
1784 if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1785 return (int)(isNeg? -v : v);
1789 ** Return the number of "v" characters in a string. Return 0 if there
1790 ** are any characters in the string other than "v".
1792 static int numberOfVChar(const char *z){
1793 int N = 0;
1794 while( z[0] && z[0]=='v' ){
1795 z++;
1796 N++;
1798 return z[0]==0 ? N : 0;
1802 ** Print sketchy documentation for this utility program
1804 static void showHelp(void){
1805 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
1806 printf(
1807 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1808 "each database, checking for crashes and memory leaks.\n"
1809 "Options:\n"
1810 " --cell-size-check Set the PRAGMA cell_size_check=ON\n"
1811 " --dbid N Use only the database where dbid=N\n"
1812 " --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n"
1813 " --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n"
1814 " --help Show this help text\n"
1815 " --info Show information about SOURCE-DB w/o running tests\n"
1816 " --limit-depth N Limit expression depth to N. Default: 500\n"
1817 " --limit-heap N Limit heap memory to N. Default: 100M\n"
1818 " --limit-mem N Limit memory used by test SQLite instance to N bytes\n"
1819 " --limit-vdbe Panic if any test runs for more than 100,000 cycles\n"
1820 " --load-sql FILE.. Load SQL scripts fron files into SOURCE-DB\n"
1821 " --load-db FILE.. Load template databases from files into SOURCE_DB\n"
1822 " --load-dbsql FILE.. Load dbsqlfuzz outputs into the xsql table\n"
1823 " ^^^^------ Use \"-\" for FILE to read filenames from stdin\n"
1824 " -m TEXT Add a description to the database\n"
1825 " --native-vfs Use the native VFS for initially empty database files\n"
1826 " --native-malloc Turn off MEMSYS3/5 and Lookaside\n"
1827 " --no-recover Do not run recovery on dbsqlfuzz databases\n"
1828 " --oss-fuzz Enable OSS-FUZZ testing\n"
1829 " --prng-seed N Seed value for the PRGN inside of SQLite\n"
1830 " -q|--quiet Reduced output\n"
1831 " --rebuild Rebuild and vacuum the database file\n"
1832 " --result-trace Show the results of each SQL command\n"
1833 " --script Output CLI script instead of running tests\n"
1834 " --skip N Skip the first N test cases\n"
1835 " --spinner Use a spinner to show progress\n"
1836 " --sqlid N Use only SQL where sqlid=N\n"
1837 " --timeout N Maximum time for any one test in N millseconds\n"
1838 " -v|--verbose Increased output. Repeat for more output.\n"
1839 " --vdbe-debug Activate VDBE debugging.\n"
1840 " --wait N Wait N seconds before continuing - useful for\n"
1841 " attaching an MSVC debugging.\n"
1845 int main(int argc, char **argv){
1846 sqlite3_int64 iBegin; /* Start time of this program */
1847 int quietFlag = 0; /* True if --quiet or -q */
1848 int verboseFlag = 0; /* True if --verbose or -v */
1849 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */
1850 int iFirstInsArg = 0; /* First argv[] for --load-db or --load-sql */
1851 sqlite3 *db = 0; /* The open database connection */
1852 sqlite3_stmt *pStmt; /* A prepared statement */
1853 int rc; /* Result code from SQLite interface calls */
1854 Blob *pSql; /* For looping over SQL scripts */
1855 Blob *pDb; /* For looping over template databases */
1856 int i; /* Loop index for the argv[] loop */
1857 int dbSqlOnly = 0; /* Only use scripts that are dbsqlfuzz */
1858 int onlySqlid = -1; /* --sqlid */
1859 int onlyDbid = -1; /* --dbid */
1860 int nativeFlag = 0; /* --native-vfs */
1861 int rebuildFlag = 0; /* --rebuild */
1862 int vdbeLimitFlag = 0; /* --limit-vdbe */
1863 int infoFlag = 0; /* --info */
1864 int nSkip = 0; /* --skip */
1865 int bScript = 0; /* --script */
1866 int bSpinner = 0; /* True for --spinner */
1867 int timeoutTest = 0; /* undocumented --timeout-test flag */
1868 int runFlags = 0; /* Flags sent to runSql() */
1869 char *zMsg = 0; /* Add this message */
1870 int nSrcDb = 0; /* Number of source databases */
1871 char **azSrcDb = 0; /* Array of source database names */
1872 int iSrcDb; /* Loop over all source databases */
1873 int nTest = 0; /* Total number of tests performed */
1874 char *zDbName = ""; /* Appreviated name of a source database */
1875 const char *zFailCode = 0; /* Value of the TEST_FAILURE env variable */
1876 int cellSzCkFlag = 0; /* --cell-size-check */
1877 int sqlFuzz = 0; /* True for SQL fuzz. False for DB fuzz */
1878 int iTimeout = 120000; /* Default 120-second timeout */
1879 int nMem = 0; /* Memory limit override */
1880 int nMemThisDb = 0; /* Memory limit set by the CONFIG table */
1881 char *zExpDb = 0; /* Write Databases to files in this directory */
1882 char *zExpSql = 0; /* Write SQL to files in this directory */
1883 void *pHeap = 0; /* Heap for use by SQLite */
1884 int ossFuzz = 0; /* enable OSS-FUZZ testing */
1885 int ossFuzzThisDb = 0; /* ossFuzz value for this particular database */
1886 int nativeMalloc = 0; /* Turn off MEMSYS3/5 and lookaside if true */
1887 sqlite3_vfs *pDfltVfs; /* The default VFS */
1888 int openFlags4Data; /* Flags for sqlite3_open_v2() */
1889 int bTimer = 0; /* Show elapse time for each test */
1890 int nV; /* How much to increase verbosity with -vvvv */
1891 sqlite3_int64 tmStart; /* Start of each test */
1893 sqlite3_config(SQLITE_CONFIG_URI,1);
1894 registerOomSimulator();
1895 sqlite3_initialize();
1896 iBegin = timeOfDay();
1897 #ifdef __unix__
1898 signal(SIGALRM, signalHandler);
1899 signal(SIGSEGV, signalHandler);
1900 signal(SIGABRT, signalHandler);
1901 #endif
1902 g.zArgv0 = argv[0];
1903 openFlags4Data = SQLITE_OPEN_READONLY;
1904 zFailCode = getenv("TEST_FAILURE");
1905 pDfltVfs = sqlite3_vfs_find(0);
1906 inmemVfsRegister(1);
1907 for(i=1; i<argc; i++){
1908 const char *z = argv[i];
1909 if( z[0]=='-' ){
1910 z++;
1911 if( z[0]=='-' ) z++;
1912 if( strcmp(z,"cell-size-check")==0 ){
1913 cellSzCkFlag = 1;
1914 }else
1915 if( strcmp(z,"dbid")==0 ){
1916 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1917 onlyDbid = integerValue(argv[++i]);
1918 }else
1919 if( strcmp(z,"export-db")==0 ){
1920 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1921 zExpDb = argv[++i];
1922 }else
1923 if( strcmp(z,"export-sql")==0 || strcmp(z,"export-dbsql")==0 ){
1924 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1925 zExpSql = argv[++i];
1926 }else
1927 if( strcmp(z,"help")==0 ){
1928 showHelp();
1929 return 0;
1930 }else
1931 if( strcmp(z,"info")==0 ){
1932 infoFlag = 1;
1933 }else
1934 if( strcmp(z,"limit-depth")==0 ){
1935 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1936 depthLimit = integerValue(argv[++i]);
1937 }else
1938 if( strcmp(z,"limit-heap")==0 ){
1939 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1940 heapLimit = integerValue(argv[++i]);
1941 }else
1942 if( strcmp(z,"limit-mem")==0 ){
1943 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1944 nMem = integerValue(argv[++i]);
1945 }else
1946 if( strcmp(z,"limit-vdbe")==0 ){
1947 vdbeLimitFlag = 1;
1948 }else
1949 if( strcmp(z,"load-sql")==0 ){
1950 zInsSql = "INSERT INTO xsql(sqltext)"
1951 "VALUES(CAST(readtextfile(?1) AS text))";
1952 iFirstInsArg = i+1;
1953 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1954 break;
1955 }else
1956 if( strcmp(z,"load-db")==0 ){
1957 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1958 iFirstInsArg = i+1;
1959 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1960 break;
1961 }else
1962 if( strcmp(z,"load-dbsql")==0 ){
1963 zInsSql = "INSERT INTO xsql(sqltext)"
1964 "VALUES(readfile(?1))";
1965 iFirstInsArg = i+1;
1966 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1967 dbSqlOnly = 1;
1968 break;
1969 }else
1970 if( strcmp(z,"m")==0 ){
1971 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1972 zMsg = argv[++i];
1973 openFlags4Data = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
1974 }else
1975 if( strcmp(z,"native-malloc")==0 ){
1976 nativeMalloc = 1;
1977 }else
1978 if( strcmp(z,"native-vfs")==0 ){
1979 nativeFlag = 1;
1980 }else
1981 if( strcmp(z,"no-recover")==0 ){
1982 bNoRecover = 1;
1983 }else
1984 if( strcmp(z,"oss-fuzz")==0 ){
1985 ossFuzz = 1;
1986 }else
1987 if( strcmp(z,"prng-seed")==0 ){
1988 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
1989 g.uRandom = atoi(argv[++i]);
1990 }else
1991 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
1992 quietFlag = 1;
1993 verboseFlag = 0;
1994 eVerbosity = 0;
1995 }else
1996 if( strcmp(z,"rebuild")==0 ){
1997 rebuildFlag = 1;
1998 openFlags4Data = SQLITE_OPEN_READWRITE;
1999 }else
2000 if( strcmp(z,"result-trace")==0 ){
2001 runFlags |= SQL_OUTPUT;
2002 }else
2003 if( strcmp(z,"script")==0 ){
2004 bScript = 1;
2005 }else
2006 if( strcmp(z,"skip")==0 ){
2007 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
2008 nSkip = atoi(argv[++i]);
2009 }else
2010 if( strcmp(z,"spinner")==0 ){
2011 bSpinner = 1;
2012 }else
2013 if( strcmp(z,"timer")==0 ){
2014 bTimer = 1;
2015 }else
2016 if( strcmp(z,"sqlid")==0 ){
2017 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
2018 onlySqlid = integerValue(argv[++i]);
2019 }else
2020 if( strcmp(z,"timeout")==0 ){
2021 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
2022 iTimeout = integerValue(argv[++i]);
2023 }else
2024 if( strcmp(z,"timeout-test")==0 ){
2025 timeoutTest = 1;
2026 #ifndef __unix__
2027 fatalError("timeout is not available on non-unix systems");
2028 #endif
2029 }else
2030 if( strcmp(z,"vdbe-debug")==0 ){
2031 bVdbeDebug = 1;
2032 }else
2033 if( strcmp(z,"verbose")==0 ){
2034 quietFlag = 0;
2035 verboseFlag++;
2036 eVerbosity++;
2037 if( verboseFlag>2 ) runFlags |= SQL_TRACE;
2038 }else
2039 if( (nV = numberOfVChar(z))>=1 ){
2040 quietFlag = 0;
2041 verboseFlag += nV;
2042 eVerbosity += nV;
2043 if( verboseFlag>2 ) runFlags |= SQL_TRACE;
2044 }else
2045 if( strcmp(z,"version")==0 ){
2046 int ii;
2047 const char *zz;
2048 printf("SQLite %s %s (%d-bit)\n",
2049 sqlite3_libversion(), sqlite3_sourceid(),
2050 8*(int)sizeof(char*));
2051 for(ii=0; (zz = sqlite3_compileoption_get(ii))!=0; ii++){
2052 printf("%s\n", zz);
2054 return 0;
2055 }else
2056 if( strcmp(z,"wait")==0 ){
2057 int iDelay;
2058 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
2059 iDelay = integerValue(argv[++i]);
2060 printf("Waiting %d seconds:", iDelay);
2061 fflush(stdout);
2062 while( 1 /*exit-by-break*/ ){
2063 sqlite3_sleep(1000);
2064 iDelay--;
2065 if( iDelay<=0 ) break;
2066 printf(" %d", iDelay);
2067 fflush(stdout);
2069 printf("\n");
2070 fflush(stdout);
2071 }else
2072 if( strcmp(z,"is-dbsql")==0 ){
2073 i++;
2074 for(i++; i<argc; i++){
2075 long nData;
2076 char *aData = readFile(argv[i], &nData);
2077 printf("%d %s\n", isDbSql((unsigned char*)aData,nData), argv[i]);
2078 sqlite3_free(aData);
2080 exit(0);
2081 }else
2083 fatalError("unknown option: %s", argv[i]);
2085 }else{
2086 nSrcDb++;
2087 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
2088 azSrcDb[nSrcDb-1] = argv[i];
2091 if( nSrcDb==0 ) fatalError("no source database specified");
2092 if( nSrcDb>1 ){
2093 if( zMsg ){
2094 fatalError("cannot change the description of more than one database");
2096 if( zInsSql ){
2097 fatalError("cannot import into more than one database");
2101 /* Process each source database separately */
2102 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
2103 char *zRawData = 0;
2104 long nRawData = 0;
2105 g.zDbFile = azSrcDb[iSrcDb];
2106 rc = sqlite3_open_v2(azSrcDb[iSrcDb], &db,
2107 openFlags4Data, pDfltVfs->zName);
2108 if( rc==SQLITE_OK ){
2109 rc = sqlite3_exec(db, "SELECT count(*) FROM sqlite_schema", 0, 0, 0);
2111 if( rc ){
2112 sqlite3_close(db);
2113 zRawData = readFile(azSrcDb[iSrcDb], &nRawData);
2114 if( zRawData==0 ){
2115 fatalError("input file \"%s\" is not recognized\n", azSrcDb[iSrcDb]);
2117 sqlite3_open(":memory:", &db);
2120 /* Print the description, if there is one */
2121 if( infoFlag ){
2122 int n;
2123 zDbName = azSrcDb[iSrcDb];
2124 i = (int)strlen(zDbName) - 1;
2125 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
2126 zDbName += i;
2127 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
2128 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2129 printf("%s: %s", zDbName, sqlite3_column_text(pStmt,0));
2130 }else{
2131 printf("%s: (empty \"readme\")", zDbName);
2133 sqlite3_finalize(pStmt);
2134 sqlite3_prepare_v2(db, "SELECT count(*) FROM db", -1, &pStmt, 0);
2135 if( pStmt
2136 && sqlite3_step(pStmt)==SQLITE_ROW
2137 && (n = sqlite3_column_int(pStmt,0))>0
2139 printf(" - %d DBs", n);
2141 sqlite3_finalize(pStmt);
2142 sqlite3_prepare_v2(db, "SELECT count(*) FROM xsql", -1, &pStmt, 0);
2143 if( pStmt
2144 && sqlite3_step(pStmt)==SQLITE_ROW
2145 && (n = sqlite3_column_int(pStmt,0))>0
2147 printf(" - %d scripts", n);
2149 sqlite3_finalize(pStmt);
2150 printf("\n");
2151 sqlite3_close(db);
2152 sqlite3_free(zRawData);
2153 continue;
2156 rc = sqlite3_exec(db,
2157 "CREATE TABLE IF NOT EXISTS db(\n"
2158 " dbid INTEGER PRIMARY KEY, -- database id\n"
2159 " dbcontent BLOB -- database disk file image\n"
2160 ");\n"
2161 "CREATE TABLE IF NOT EXISTS xsql(\n"
2162 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n"
2163 " sqltext TEXT -- Text of SQL statements to run\n"
2164 ");"
2165 "CREATE TABLE IF NOT EXISTS readme(\n"
2166 " msg TEXT -- Human-readable description of this file\n"
2167 ");", 0, 0, 0);
2168 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
2169 if( zMsg ){
2170 char *zSql;
2171 zSql = sqlite3_mprintf(
2172 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
2173 rc = sqlite3_exec(db, zSql, 0, 0, 0);
2174 sqlite3_free(zSql);
2175 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
2177 if( zRawData ){
2178 zInsSql = "INSERT INTO xsql(sqltext) VALUES(?1)";
2179 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
2180 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2181 zInsSql, sqlite3_errmsg(db));
2182 sqlite3_bind_text(pStmt, 1, zRawData, nRawData, SQLITE_STATIC);
2183 sqlite3_step(pStmt);
2184 rc = sqlite3_reset(pStmt);
2185 if( rc ) fatalError("insert failed for %s", argv[i]);
2186 sqlite3_finalize(pStmt);
2187 rebuild_database(db, dbSqlOnly);
2188 zInsSql = 0;
2189 sqlite3_free(zRawData);
2190 zRawData = 0;
2192 ossFuzzThisDb = ossFuzz;
2194 /* If the CONFIG(name,value) table exists, read db-specific settings
2195 ** from that table */
2196 if( sqlite3_table_column_metadata(db,0,"config",0,0,0,0,0,0)==SQLITE_OK ){
2197 rc = sqlite3_prepare_v2(db, "SELECT name, value FROM config",
2198 -1, &pStmt, 0);
2199 if( rc ) fatalError("cannot prepare query of CONFIG table: %s",
2200 sqlite3_errmsg(db));
2201 while( SQLITE_ROW==sqlite3_step(pStmt) ){
2202 const char *zName = (const char *)sqlite3_column_text(pStmt,0);
2203 if( zName==0 ) continue;
2204 if( strcmp(zName, "oss-fuzz")==0 ){
2205 ossFuzzThisDb = sqlite3_column_int(pStmt,1);
2206 if( verboseFlag>1 ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb);
2208 if( strcmp(zName, "limit-mem")==0 ){
2209 nMemThisDb = sqlite3_column_int(pStmt,1);
2210 if( verboseFlag>1 ) printf("Config: limit-mem=%d\n", nMemThisDb);
2213 sqlite3_finalize(pStmt);
2216 if( zInsSql ){
2217 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
2218 readfileFunc, 0, 0);
2219 sqlite3_create_function(db, "readtextfile", 1, SQLITE_UTF8, 0,
2220 readtextfileFunc, 0, 0);
2221 sqlite3_create_function(db, "isdbsql", 1, SQLITE_UTF8, 0,
2222 isDbSqlFunc, 0, 0);
2223 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
2224 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2225 zInsSql, sqlite3_errmsg(db));
2226 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
2227 if( rc ) fatalError("cannot start a transaction");
2228 for(i=iFirstInsArg; i<argc; i++){
2229 if( strcmp(argv[i],"-")==0 ){
2230 /* A filename of "-" means read multiple filenames from stdin */
2231 char zLine[2000];
2232 while( rc==0 && fgets(zLine,sizeof(zLine),stdin)!=0 ){
2233 size_t kk = strlen(zLine);
2234 while( kk>0 && zLine[kk-1]<=' ' ) kk--;
2235 sqlite3_bind_text(pStmt, 1, zLine, (int)kk, SQLITE_STATIC);
2236 if( verboseFlag>1 ) printf("loading %.*s\n", (int)kk, zLine);
2237 sqlite3_step(pStmt);
2238 rc = sqlite3_reset(pStmt);
2239 if( rc ) fatalError("insert failed for %s", zLine);
2241 }else{
2242 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
2243 if( verboseFlag>1 ) printf("loading %s\n", argv[i]);
2244 sqlite3_step(pStmt);
2245 rc = sqlite3_reset(pStmt);
2246 if( rc ) fatalError("insert failed for %s", argv[i]);
2249 sqlite3_finalize(pStmt);
2250 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
2251 if( rc ) fatalError("cannot commit the transaction: %s",
2252 sqlite3_errmsg(db));
2253 rebuild_database(db, dbSqlOnly);
2254 sqlite3_close(db);
2255 return 0;
2257 rc = sqlite3_exec(db, "PRAGMA query_only=1;", 0, 0, 0);
2258 if( rc ) fatalError("cannot set database to query-only");
2259 if( zExpDb!=0 || zExpSql!=0 ){
2260 sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
2261 writefileFunc, 0, 0);
2262 if( zExpDb!=0 ){
2263 const char *zExDb =
2264 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
2265 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
2266 " FROM db WHERE ?2<0 OR dbid=?2;";
2267 rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
2268 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2269 zExDb, sqlite3_errmsg(db));
2270 sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
2271 SQLITE_STATIC, SQLITE_UTF8);
2272 sqlite3_bind_int(pStmt, 2, onlyDbid);
2273 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2274 printf("write db-%d (%d bytes) into %s\n",
2275 sqlite3_column_int(pStmt,1),
2276 sqlite3_column_int(pStmt,3),
2277 sqlite3_column_text(pStmt,2));
2279 sqlite3_finalize(pStmt);
2281 if( zExpSql!=0 ){
2282 const char *zExSql =
2283 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
2284 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
2285 " FROM xsql WHERE ?2<0 OR sqlid=?2;";
2286 rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
2287 if( rc ) fatalError("cannot prepare statement [%s]: %s",
2288 zExSql, sqlite3_errmsg(db));
2289 sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
2290 SQLITE_STATIC, SQLITE_UTF8);
2291 sqlite3_bind_int(pStmt, 2, onlySqlid);
2292 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2293 printf("write sql-%d (%d bytes) into %s\n",
2294 sqlite3_column_int(pStmt,1),
2295 sqlite3_column_int(pStmt,3),
2296 sqlite3_column_text(pStmt,2));
2298 sqlite3_finalize(pStmt);
2300 sqlite3_close(db);
2301 return 0;
2304 /* Load all SQL script content and all initial database images from the
2305 ** source db
2307 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
2308 &g.nSql, &g.pFirstSql);
2309 if( g.nSql==0 ) fatalError("need at least one SQL script");
2310 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
2311 &g.nDb, &g.pFirstDb);
2312 if( g.nDb==0 ){
2313 g.pFirstDb = safe_realloc(0, sizeof(Blob));
2314 memset(g.pFirstDb, 0, sizeof(Blob));
2315 g.pFirstDb->id = 1;
2316 g.pFirstDb->seq = 0;
2317 g.nDb = 1;
2318 sqlFuzz = 1;
2321 /* Print the description, if there is one */
2322 if( !quietFlag && !bScript ){
2323 zDbName = azSrcDb[iSrcDb];
2324 i = (int)strlen(zDbName) - 1;
2325 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
2326 zDbName += i;
2327 if( verboseFlag ){
2328 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
2329 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2330 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
2332 sqlite3_finalize(pStmt);
2336 /* Rebuild the database, if requested */
2337 if( rebuildFlag ){
2338 if( !quietFlag ){
2339 printf("%s: rebuilding... ", zDbName);
2340 fflush(stdout);
2342 rebuild_database(db, 0);
2343 if( !quietFlag ) printf("done\n");
2346 /* Close the source database. Verify that no SQLite memory allocations are
2347 ** outstanding.
2349 sqlite3_close(db);
2350 if( sqlite3_memory_used()>0 ){
2351 fatalError("SQLite has memory in use before the start of testing");
2354 /* Limit available memory, if requested */
2355 sqlite3_shutdown();
2357 if( nMemThisDb>0 && nMem==0 ){
2358 if( !nativeMalloc ){
2359 pHeap = realloc(pHeap, nMemThisDb);
2360 if( pHeap==0 ){
2361 fatalError("failed to allocate %d bytes of heap memory", nMem);
2363 sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMemThisDb, 128);
2364 }else{
2365 sqlite3_hard_heap_limit64((sqlite3_int64)nMemThisDb);
2367 }else{
2368 sqlite3_hard_heap_limit64(0);
2371 /* Disable lookaside with the --native-malloc option */
2372 if( nativeMalloc ){
2373 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
2376 /* Reset the in-memory virtual filesystem */
2377 formatVfs();
2379 /* Run a test using each SQL script against each database.
2381 if( verboseFlag<2 && !quietFlag && !bSpinner && !bScript ){
2382 printf("%s:", zDbName);
2384 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
2385 tmStart = timeOfDay();
2386 if( isDbSql(pSql->a, pSql->sz) ){
2387 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d",pSql->id);
2388 if( bScript ){
2389 /* No progress output */
2390 }else if( bSpinner ){
2391 int nTotal =g.nSql;
2392 int idx = pSql->seq;
2393 printf("\r%s: %d/%d ", zDbName, idx, nTotal);
2394 fflush(stdout);
2395 }else if( verboseFlag>1 ){
2396 printf("%s\n", g.zTestName);
2397 fflush(stdout);
2398 }else if( !quietFlag ){
2399 static int prevAmt = -1;
2400 int idx = pSql->seq;
2401 int amt = idx*10/(g.nSql);
2402 if( amt!=prevAmt ){
2403 printf(" %d%%", amt*10);
2404 fflush(stdout);
2405 prevAmt = amt;
2408 if( nSkip>0 ){
2409 nSkip--;
2410 }else{
2411 runCombinedDbSqlInput(pSql->a, pSql->sz, iTimeout, bScript, pSql->id);
2413 nTest++;
2414 if( bTimer && !bScript ){
2415 sqlite3_int64 tmEnd = timeOfDay();
2416 printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2418 g.zTestName[0] = 0;
2419 disableOom();
2420 continue;
2422 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
2423 int openFlags;
2424 const char *zVfs = "inmem";
2425 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
2426 pSql->id, pDb->id);
2427 if( bScript ){
2428 /* No progress output */
2429 }else if( bSpinner ){
2430 int nTotal = g.nDb*g.nSql;
2431 int idx = pSql->seq*g.nDb + pDb->id - 1;
2432 printf("\r%s: %d/%d ", zDbName, idx, nTotal);
2433 fflush(stdout);
2434 }else if( verboseFlag>1 ){
2435 printf("%s\n", g.zTestName);
2436 fflush(stdout);
2437 }else if( !quietFlag ){
2438 static int prevAmt = -1;
2439 int idx = pSql->seq*g.nDb + pDb->id - 1;
2440 int amt = idx*10/(g.nDb*g.nSql);
2441 if( amt!=prevAmt ){
2442 printf(" %d%%", amt*10);
2443 fflush(stdout);
2444 prevAmt = amt;
2447 if( nSkip>0 ){
2448 nSkip--;
2449 continue;
2451 if( bScript ){
2452 char zName[100];
2453 sqlite3_snprintf(sizeof(zName), zName, "db%06d.db",
2454 pDb->id>1 ? pDb->id : pSql->id);
2455 renderDbSqlForCLI(stdout, zName,
2456 pDb->a, pDb->sz, pSql->a, pSql->sz);
2457 continue;
2459 createVFile("main.db", pDb->sz, pDb->a);
2460 sqlite3_randomness(0,0);
2461 if( ossFuzzThisDb ){
2462 #ifndef SQLITE_OSS_FUZZ
2463 fatalError("--oss-fuzz not supported: recompile"
2464 " with -DSQLITE_OSS_FUZZ");
2465 #else
2466 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
2467 LLVMFuzzerTestOneInput((const uint8_t*)pSql->a, (size_t)pSql->sz);
2468 #endif
2469 }else{
2470 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
2471 if( nativeFlag && pDb->sz==0 ){
2472 openFlags |= SQLITE_OPEN_MEMORY;
2473 zVfs = 0;
2475 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
2476 if( rc ) fatalError("cannot open inmem database");
2477 sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 100000000);
2478 sqlite3_limit(db, SQLITE_LIMIT_LIKE_PATTERN_LENGTH, 50);
2479 if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
2480 setAlarm((iTimeout+999)/1000);
2481 /* Enable test functions */
2482 sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, db);
2483 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2484 if( sqlFuzz || vdbeLimitFlag ){
2485 sqlite3_progress_handler(db, 100000, progressHandler,
2486 &vdbeLimitFlag);
2488 #endif
2489 #ifdef SQLITE_TESTCTRL_PRNG_SEED
2490 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, 1, db);
2491 #endif
2492 if( bVdbeDebug ){
2493 sqlite3_exec(db, "PRAGMA vdbe_debug=ON", 0, 0, 0);
2496 runSql(db, (char*)pSql->a, runFlags);
2497 }while( timeoutTest );
2498 setAlarm(0);
2499 sqlite3_exec(db, "PRAGMA temp_store_directory=''", 0, 0, 0);
2500 sqlite3_close(db);
2502 if( sqlite3_memory_used()>0 ){
2503 fatalError("memory leak: %lld bytes outstanding",
2504 sqlite3_memory_used());
2506 reformatVfs();
2507 nTest++;
2508 if( bTimer ){
2509 sqlite3_int64 tmEnd = timeOfDay();
2510 printf("%lld %s\n", tmEnd - tmStart, g.zTestName);
2512 g.zTestName[0] = 0;
2514 /* Simulate an error if the TEST_FAILURE environment variable is "5".
2515 ** This is used to verify that automated test script really do spot
2516 ** errors that occur in this test program.
2518 if( zFailCode ){
2519 if( zFailCode[0]=='5' && zFailCode[1]==0 ){
2520 fatalError("simulated failure");
2521 }else if( zFailCode[0]!=0 ){
2522 /* If TEST_FAILURE is something other than 5, just exit the test
2523 ** early */
2524 printf("\nExit early due to TEST_FAILURE being set\n");
2525 iSrcDb = nSrcDb-1;
2526 goto sourcedb_cleanup;
2531 if( bScript ){
2532 /* No progress output */
2533 }else if( bSpinner ){
2534 int nTotal = g.nDb*g.nSql;
2535 printf("\r%s: %d/%d \n", zDbName, nTotal, nTotal);
2536 }else if( !quietFlag && verboseFlag<2 ){
2537 printf(" 100%% - %d tests\n", g.nDb*g.nSql);
2540 /* Clean up at the end of processing a single source database
2542 sourcedb_cleanup:
2543 blobListFree(g.pFirstSql);
2544 blobListFree(g.pFirstDb);
2545 reformatVfs();
2547 } /* End loop over all source databases */
2549 if( !quietFlag && !bScript ){
2550 sqlite3_int64 iElapse = timeOfDay() - iBegin;
2551 if( g.nInvariant ){
2552 printf("fuzzcheck: %u query invariants checked\n", g.nInvariant);
2554 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
2555 "SQLite %s %s (%d-bit)\n",
2556 nTest, (int)(iElapse/1000), (int)(iElapse%1000),
2557 sqlite3_libversion(), sqlite3_sourceid(),
2558 8*(int)sizeof(char*));
2560 free(azSrcDb);
2561 free(pHeap);
2562 return 0;