4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
20 ** dbid INTEGER PRIMARY KEY, -- database id
21 ** dbcontent BLOB -- database disk file image
24 ** sqlid INTEGER PRIMARY KEY, -- SQL script id
25 ** sqltext TEXT -- Text of SQL statements to run
27 ** CREATE TABLE IF NOT EXISTS readme(
28 ** msg TEXT -- Human-readable description of this test collection
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.
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
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.
88 #include "sqlite3recover.h"
89 #define ISSPACE(X) isspace((unsigned char)(X))
90 #define ISDIGIT(X) isdigit((unsigned char)(X))
99 #if !defined(_MSC_VER)
103 #if defined(_MSC_VER)
104 typedef unsigned char uint8_t;
108 ** Files in the virtual file system.
110 typedef struct VFile 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
;
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
;
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.
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 */
162 ** Include the external vt02.c module.
164 extern int sqlite3_vt02_init(sqlite3
*,char***,void*);
168 ** Print an error message and quit.
170 static void fatalError(const char *zFormat
, ...){
172 fprintf(stderr
, "%s", g
.zArgv0
);
173 if( g
.zDbFile
) fprintf(stderr
, " %s", g
.zDbFile
);
174 if( g
.zTestName
[0] ) fprintf(stderr
, " (%s)", g
.zTestName
);
175 fprintf(stderr
, ": ");
176 va_start(ap
, zFormat
);
177 vfprintf(stderr
, zFormat
, ap
);
179 fprintf(stderr
, "\n");
187 static void signalHandler(int signum
){
189 if( signum
==SIGABRT
){
191 }else if( signum
==SIGALRM
){
193 }else if( signum
==SIGSEGV
){
203 ** Set the an alarm to go off after N seconds. Disable the alarm
206 static void setAlarm(int N
){
214 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
216 ** This an SQL progress handler. After an SQL statement has run for
217 ** many steps, we want to interrupt it. This guards against infinite
218 ** loops from recursive common table expressions.
220 ** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
221 ** In that case, hitting the progress handler is a fatal error.
223 static int progressHandler(void *pVdbeLimitFlag
){
224 if( *(int*)pVdbeLimitFlag
) fatalError("too many VDBE cycles");
230 ** Reallocate memory. Show an error and quit if unable.
232 static void *safe_realloc(void *pOld
, int szNew
){
233 void *pNew
= realloc(pOld
, szNew
<=0 ? 1 : szNew
);
234 if( pNew
==0 ) fatalError("unable to realloc for %d bytes", szNew
);
239 ** Initialize the virtual file system.
241 static void formatVfs(void){
243 for(i
=0; i
<MX_FILE
; i
++){
245 g
.aFile
[i
].zFilename
= 0;
253 ** Erase all information in the virtual file system.
255 static void reformatVfs(void){
257 for(i
=0; i
<MX_FILE
; i
++){
258 if( g
.aFile
[i
].sz
<0 ) continue;
259 if( g
.aFile
[i
].zFilename
){
260 free(g
.aFile
[i
].zFilename
);
261 g
.aFile
[i
].zFilename
= 0;
263 if( g
.aFile
[i
].nRef
>0 ){
264 fatalError("file %d still open. nRef=%d", i
, g
.aFile
[i
].nRef
);
274 ** Find a VFile by name
276 static VFile
*findVFile(const char *zName
){
278 if( zName
==0 ) return 0;
279 for(i
=0; i
<MX_FILE
; i
++){
280 if( g
.aFile
[i
].zFilename
==0 ) continue;
281 if( strcmp(g
.aFile
[i
].zFilename
, zName
)==0 ) return &g
.aFile
[i
];
287 ** Find a VFile by name. Create it if it does not already exist and
288 ** initialize it to the size and content given.
290 ** Return NULL only if the filesystem is full.
292 static VFile
*createVFile(const char *zName
, int sz
, unsigned char *pData
){
293 VFile
*pNew
= findVFile(zName
);
295 if( pNew
) return pNew
;
296 for(i
=0; i
<MX_FILE
&& g
.aFile
[i
].sz
>=0; i
++){}
297 if( i
>=MX_FILE
) return 0;
300 int nName
= (int)strlen(zName
)+1;
301 pNew
->zFilename
= safe_realloc(0, nName
);
302 memcpy(pNew
->zFilename
, zName
, nName
);
308 pNew
->a
= safe_realloc(0, sz
);
309 if( sz
>0 ) memcpy(pNew
->a
, pData
, sz
);
313 /* Return true if the line is all zeros */
314 static int allZero(unsigned char *aLine
){
316 for(i
=0; i
<16 && aLine
[i
]==0; i
++){}
321 ** Render a database and query as text that can be input into
324 static void renderDbSqlForCLI(
325 FILE *out
, /* Write to this file */
326 const char *zFile
, /* Name of the database file */
327 unsigned char *aDb
, /* Database content */
328 int nDb
, /* Number of bytes in aDb[] */
329 unsigned char *zSql
, /* SQL content */
330 int nSql
/* Bytes of SQL */
332 fprintf(out
, ".print ******* %s *******\n", zFile
);
334 int i
, j
; /* Loop counters */
335 int pgsz
; /* Size of each page */
336 int lastPage
= 0; /* Last page number shown */
337 int iPage
; /* Current page number */
338 unsigned char *aLine
; /* Single line to display */
339 unsigned char buf
[16]; /* Fake line */
340 unsigned char bShow
[256]; /* Characters ok to display */
342 memset(bShow
, '.', sizeof(bShow
));
343 for(i
=' '; i
<='~'; i
++){
344 if( i
!='{' && i
!='}' && i
!='"' && i
!='\\' ) bShow
[i
] = i
;
346 pgsz
= (aDb
[16]<<8) | aDb
[17];
347 if( pgsz
==0 ) pgsz
= 65536;
348 if( pgsz
<512 || (pgsz
&(pgsz
-1))!=0 ) pgsz
= 4096;
349 fprintf(out
,".open --hexdb\n");
350 fprintf(out
,"| size %d pagesize %d filename %s\n",nDb
,pgsz
,zFile
);
351 for(i
=0; i
<nDb
; i
+= 16){
353 memset(buf
, 0, sizeof(buf
));
354 memcpy(buf
, aDb
+i
, nDb
-i
);
359 if( allZero(aLine
) ) continue;
361 if( lastPage
!=iPage
){
362 fprintf(out
,"| page %d offset %d\n", iPage
, (iPage
-1)*pgsz
);
365 fprintf(out
,"| %5d:", i
-(iPage
-1)*pgsz
);
366 for(j
=0; j
<16; j
++) fprintf(out
," %02x", aLine
[j
]);
369 unsigned char c
= (unsigned char)aLine
[j
];
370 fputc( bShow
[c
], stdout
);
374 fprintf(out
,"| end %s\n", zFile
);
376 fprintf(out
,".open :memory:\n");
378 fprintf(out
,".testctrl prng_seed 1 db\n");
379 fprintf(out
,".testctrl internal_functions\n");
380 fprintf(out
,"%.*s", nSql
, zSql
);
381 if( nSql
>0 && zSql
[nSql
-1]!='\n' ) fprintf(out
, "\n");
385 ** Read the complete content of a file into memory. Add a 0x00 terminator
386 ** and return a pointer to the result.
388 ** The file content is held in memory obtained from sqlite_malloc64() which
389 ** should be freed by the caller.
391 static char *readFile(const char *zFilename
, long *sz
){
397 if( zFilename
==0 ) return 0;
398 in
= fopen(zFilename
, "rb");
399 if( in
==0 ) return 0;
400 fseek(in
, 0, SEEK_END
);
401 *sz
= nIn
= ftell(in
);
403 pBuf
= sqlite3_malloc64( nIn
+1 );
404 if( pBuf
&& 1==fread(pBuf
, nIn
, 1, in
) ){
417 ** Implementation of the "readfile(X)" SQL function. The entire content
418 ** of the file named X is read and returned as a BLOB. NULL is returned
419 ** if the file does not exist or is unreadable.
421 static void readfileFunc(
422 sqlite3_context
*context
,
428 const char *zName
= (const char*)sqlite3_value_text(argv
[0]);
430 if( zName
==0 ) return;
431 pBuf
= readFile(zName
, &nIn
);
433 sqlite3_result_blob(context
, pBuf
, nIn
, sqlite3_free
);
438 ** Implementation of the "readtextfile(X)" SQL function. The text content
439 ** of the file named X through the end of the file or to the first \000
440 ** character, whichever comes first, is read and returned as TEXT. NULL
441 ** is returned if the file does not exist or is unreadable.
443 static void readtextfileFunc(
444 sqlite3_context
*context
,
453 zName
= (const char*)sqlite3_value_text(argv
[0]);
454 if( zName
==0 ) return;
455 in
= fopen(zName
, "rb");
457 fseek(in
, 0, SEEK_END
);
460 pBuf
= sqlite3_malloc64( nIn
+1 );
461 if( pBuf
&& 1==fread(pBuf
, nIn
, 1, in
) ){
463 sqlite3_result_text(context
, pBuf
, -1, sqlite3_free
);
471 ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
472 ** is written into file X. The number of bytes written is returned. Or
473 ** NULL is returned if something goes wrong, such as being unable to open
474 ** file X for writing.
476 static void writefileFunc(
477 sqlite3_context
*context
,
487 zFile
= (const char*)sqlite3_value_text(argv
[0]);
488 if( zFile
==0 ) return;
489 out
= fopen(zFile
, "wb");
491 z
= (const char*)sqlite3_value_blob(argv
[1]);
495 rc
= fwrite(z
, 1, sqlite3_value_bytes(argv
[1]), out
);
498 sqlite3_result_int64(context
, rc
);
503 ** Load a list of Blob objects from the database
505 static void blobListLoadFromDb(
506 sqlite3
*db
, /* Read from this database */
507 const char *zSql
, /* Query used to extract the blobs */
508 int onlyId
, /* Only load where id is this value */
509 int *pN
, /* OUT: Write number of blobs loaded here */
510 Blob
**ppList
/* OUT: Write the head of the blob list here */
520 z2
= sqlite3_mprintf("%s WHERE rowid=%d", zSql
, onlyId
);
522 z2
= sqlite3_mprintf("%s", zSql
);
524 rc
= sqlite3_prepare_v2(db
, z2
, -1, &pStmt
, 0);
526 if( rc
) fatalError("%s", sqlite3_errmsg(db
));
529 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
530 int sz
= sqlite3_column_bytes(pStmt
, 1);
531 Blob
*pNew
= safe_realloc(0, sizeof(*pNew
)+sz
);
532 pNew
->id
= sqlite3_column_int(pStmt
, 0);
536 memcpy(pNew
->a
, sqlite3_column_blob(pStmt
,1), sz
);
541 sqlite3_finalize(pStmt
);
543 *ppList
= head
.pNext
;
547 ** Free a list of Blob objects
549 static void blobListFree(Blob
*p
){
558 /* Return the current wall-clock time
560 ** The number of milliseconds since the julian epoch.
561 ** 1907-01-01 00:00:00 -> 210866716800000
562 ** 2021-01-01 00:00:00 -> 212476176000000
564 static sqlite3_int64
timeOfDay(void){
565 static sqlite3_vfs
*clockVfs
= 0;
568 clockVfs
= sqlite3_vfs_find(0);
569 if( clockVfs
==0 ) return 0;
571 if( clockVfs
->iVersion
>=1 && clockVfs
->xCurrentTimeInt64
!=0 ){
572 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
575 clockVfs
->xCurrentTime(clockVfs
, &r
);
576 t
= (sqlite3_int64
)(r
*86400000.0);
581 /***************************************************************************
582 ** Code to process combined database+SQL scripts generated by the
586 /* An instance of the following object is passed by pointer as the
587 ** client data to various callbacks.
589 typedef struct FuzzCtx
{
590 sqlite3
*db
; /* The database connection */
591 sqlite3_int64 iCutoffTime
; /* Stop processing at this time. */
592 sqlite3_int64 iLastCb
; /* Time recorded for previous progress callback */
593 sqlite3_int64 mxInterval
; /* Longest interval between two progress calls */
594 unsigned nCb
; /* Number of progress callbacks */
595 unsigned mxCb
; /* Maximum number of progress callbacks allowed */
596 unsigned execCnt
; /* Number of calls to the sqlite3_exec callback */
597 int timeoutHit
; /* True when reaching a timeout */
600 /* Verbosity level for the dbsqlfuzz test runner */
601 static int eVerbosity
= 0;
603 /* True to activate PRAGMA vdbe_debug=on */
604 static int bVdbeDebug
= 0;
606 /* Timeout for each fuzzing attempt, in milliseconds */
607 static int giTimeout
= 10000; /* Defaults to 10 seconds */
609 /* Maximum number of progress handler callbacks */
610 static unsigned int mxProgressCb
= 2000;
612 /* Maximum string length in SQLite */
613 static int lengthLimit
= 1000000;
615 /* Maximum expression depth */
616 static int depthLimit
= 500;
618 /* Limit on the amount of heap memory that can be used */
619 static sqlite3_int64 heapLimit
= 100000000;
621 /* Maximum byte-code program length in SQLite */
622 static int vdbeOpLimit
= 25000;
624 /* Maximum size of the in-memory database */
625 static sqlite3_int64 maxDbSize
= 104857600;
626 /* OOM simulation parameters */
627 static unsigned int oomCounter
= 0; /* Simulate OOM when equals 1 */
628 static unsigned int oomRepeat
= 0; /* Number of OOMs in a row */
629 static void*(*defaultMalloc
)(int) = 0; /* The low-level malloc routine */
631 /* Enable recovery */
632 static int bNoRecover
= 0;
634 /* This routine is called when a simulated OOM occurs. It is broken
635 ** out as a separate routine to make it easy to set a breakpoint on
640 printf("Simulated OOM fault\n");
649 /* This routine is a replacement malloc() that is used to simulate
650 ** Out-Of-Memory (OOM) errors for testing purposes.
652 static void *oomMalloc(int nByte
){
661 return defaultMalloc(nByte
);
664 /* Register the OOM simulator. This must occur before any memory
666 static void registerOomSimulator(void){
667 sqlite3_mem_methods mem
;
669 sqlite3_config(SQLITE_CONFIG_GETMALLOC
, &mem
);
670 defaultMalloc
= mem
.xMalloc
;
671 mem
.xMalloc
= oomMalloc
;
672 sqlite3_config(SQLITE_CONFIG_MALLOC
, &mem
);
675 /* Turn off any pending OOM simulation */
676 static void disableOom(void){
682 ** Translate a single byte of Hex into an integer.
683 ** This routine only works if h really is a valid hexadecimal
684 ** character: 0..9a..fA..F
686 static unsigned char hexToInt(unsigned int h
){
688 h
+= 9*(1&~(h
>>4)); /* EBCDIC */
690 h
+= 9*(1&(h
>>6)); /* ASCII */
696 ** The first character of buffer zIn[0..nIn-1] is a '['. This routine
697 ** checked to see if the buffer holds "[NNNN]" or "[+NNNN]" and if it
698 ** does it makes corresponding changes to the *pK value and *pI value
699 ** and returns true. If the input buffer does not match the patterns,
700 ** no changes are made to either *pK or *pI and this routine returns false.
703 const unsigned char *zIn
, /* Text input */
704 int nIn
, /* Bytes of input */
705 unsigned int *pK
, /* half-byte cursor to adjust */
706 unsigned int *pI
/* Input index to adjust */
711 for(i
=1; i
<nIn
&& (c
= zIn
[i
])!=']'; i
++){
712 if( !isxdigit(c
) ) return 0;
713 k
= k
*16 + hexToInt(c
);
715 if( i
==nIn
) return 0;
722 ** Decode the text starting at zIn into a binary database file.
723 ** The maximum length of zIn is nIn bytes. Store the binary database
724 ** file in space obtained from sqlite3_malloc().
726 ** Return the number of bytes of zIn consumed. Or return -1 if there
727 ** is an error. One potential error is that the recipe specifies a
728 ** database file larger than MX_FILE_SZ bytes.
732 static int decodeDatabase(
733 const unsigned char *zIn
, /* Input text to be decoded */
734 int nIn
, /* Bytes of input text */
735 unsigned char **paDecode
, /* OUT: decoded database file */
736 int *pnDecode
/* OUT: Size of decoded database */
738 unsigned char *a
, *aNew
; /* Database under construction */
739 int mx
= 0; /* Current size of the database */
740 sqlite3_uint64 nAlloc
= 4096; /* Space allocated in a[] */
741 unsigned int i
; /* Next byte of zIn[] to read */
742 unsigned int j
; /* Temporary integer */
743 unsigned int k
; /* half-byte cursor index for output */
744 unsigned int n
; /* Number of bytes of input */
746 if( nIn
<4 ) return -1;
747 n
= (unsigned int)nIn
;
748 a
= sqlite3_malloc64( nAlloc
);
750 fprintf(stderr
, "Out of memory!\n");
753 memset(a
, 0, (size_t)nAlloc
);
754 for(i
=k
=0; i
<n
; i
++){
755 unsigned char c
= (unsigned char)zIn
[i
];
764 sqlite3_uint64 newSize
;
765 if( nAlloc
==MX_FILE_SZ
|| j
>=MX_FILE_SZ
){
767 fprintf(stderr
, "Input database too big: max %d bytes\n",
775 newSize
= (j
+4096)&~4095;
777 if( newSize
>MX_FILE_SZ
){
782 newSize
= MX_FILE_SZ
;
784 aNew
= sqlite3_realloc64( a
, newSize
);
790 assert( newSize
> nAlloc
);
791 memset(a
+nAlloc
, 0, (size_t)(newSize
- nAlloc
));
794 if( j
>=(unsigned)mx
){
795 mx
= (j
+ 4095)&~4095;
796 if( mx
>MX_FILE_SZ
) mx
= MX_FILE_SZ
;
801 }else if( zIn
[i
]=='[' && i
<n
-3 && isOffset(zIn
+i
, nIn
-i
, &k
, &i
) ){
803 }else if( zIn
[i
]=='\n' && i
<n
-4 && memcmp(zIn
+i
,"\n--\n",4)==0 ){
814 ** Progress handler callback.
816 ** The argument is the cutoff-time after which all processing should
817 ** stop. So return non-zero if the cut-off time is exceeded.
819 static int progress_handler(void *pClientData
) {
820 FuzzCtx
*p
= (FuzzCtx
*)pClientData
;
821 sqlite3_int64 iNow
= timeOfDay();
822 int rc
= iNow
>=p
->iCutoffTime
;
823 sqlite3_int64 iDiff
= iNow
- p
->iLastCb
;
824 /* printf("time-remaining: %lld\n", p->iCutoffTime - iNow); */
825 if( iDiff
> p
->mxInterval
) p
->mxInterval
= iDiff
;
827 if( rc
==0 && p
->mxCb
>0 && p
->mxCb
<=p
->nCb
) rc
= 1;
828 if( rc
&& !p
->timeoutHit
&& eVerbosity
>=2 ){
829 printf("Timeout on progress callback %d\n", p
->nCb
);
837 ** Flag bits set by block_troublesome_sql()
839 #define BTS_SELECT 0x000001
840 #define BTS_NONSELECT 0x000002
841 #define BTS_BADFUNC 0x000004
842 #define BTS_BADPRAGMA 0x000008 /* Sticky for rest of the script */
845 ** Disallow debugging pragmas such as "PRAGMA vdbe_debug" and
846 ** "PRAGMA parser_trace" since they can dramatically increase the
847 ** amount of output without actually testing anything useful.
849 ** Also block ATTACH if attaching a file from the filesystem.
851 static int block_troublesome_sql(
859 unsigned int *pBtsFlags
= (unsigned int*)pClientData
;
864 case SQLITE_PRAGMA
: {
865 if( sqlite3_stricmp("busy_timeout",zArg1
)==0
866 && (zArg2
==0 || strtoll(zArg2
,0,0)>100 || strtoll(zArg2
,0,10)>100)
869 }else if( sqlite3_stricmp("hard_heap_limit", zArg1
)==0
870 || sqlite3_stricmp("reverse_unordered_selects", zArg1
)==0
872 /* BTS_BADPRAGMA is sticky. A hard_heap_limit or
873 ** revert_unordered_selects should inhibit all future attempts
874 ** at verifying query invariants */
875 *pBtsFlags
|= BTS_BADPRAGMA
;
876 }else if( eVerbosity
==0 ){
877 if( sqlite3_strnicmp("vdbe_", zArg1
, 5)==0
878 || sqlite3_stricmp("parser_trace", zArg1
)==0
879 || sqlite3_stricmp("temp_store_directory", zArg1
)==0
883 }else if( sqlite3_stricmp("oom",zArg1
)==0
884 && zArg2
!=0 && zArg2
[0]!=0 ){
885 oomCounter
= atoi(zArg2
);
887 *pBtsFlags
|= BTS_NONSELECT
;
890 case SQLITE_ATTACH
: {
891 /* Deny the ATTACH if it is attaching anything other than an in-memory
893 *pBtsFlags
|= BTS_NONSELECT
;
894 if( zArg1
==0 ) return SQLITE_DENY
;
895 if( strcmp(zArg1
,":memory:")==0 ) return SQLITE_OK
;
896 if( sqlite3_strglob("file:*[?]vfs=memdb", zArg1
)==0
897 && sqlite3_strglob("file:*[^/a-zA-Z0-9_.]*[?]vfs=memdb", zArg1
)!=0
903 case SQLITE_SELECT
: {
904 *pBtsFlags
|= BTS_SELECT
;
907 case SQLITE_FUNCTION
: {
908 static const char *azBadFuncs
[] = {
920 "geopoly_group_bbox",
922 "implies_nonnull_row",
947 last
= sizeof(azBadFuncs
)/sizeof(azBadFuncs
[0]) - 1;
949 int mid
= (first
+last
)/2;
950 int c
= sqlite3_stricmp(azBadFuncs
[mid
], zArg2
);
956 *pBtsFlags
|= BTS_BADFUNC
;
959 }while( first
<=last
);
967 *pBtsFlags
|= BTS_NONSELECT
;
973 /* Implementation found in fuzzinvariant.c */
974 extern int fuzz_invariant(
975 sqlite3
*db
, /* The database connection */
976 sqlite3_stmt
*pStmt
, /* Test statement stopped on an SQLITE_ROW */
977 int iCnt
, /* Invariant sequence number, starting at 0 */
978 int iRow
, /* The row number for pStmt */
979 int nRow
, /* Total number of output rows */
980 int *pbCorrupt
, /* IN/OUT: Flag indicating a corrupt database file */
981 int eVerbosity
/* How much debugging output */
984 /* Implementation of sqlite_dbdata and sqlite_dbptr */
985 extern int sqlite3_dbdata_init(sqlite3
*,const char**,void*);
989 ** This function is used as a callback by the recover extension. Simply
990 ** print the supplied SQL statement to stdout.
992 static int recoverSqlCb(void *pCtx
, const char *zSql
){
994 printf("%s\n", zSql
);
1000 ** This function is called to recover data from the database.
1002 static int recoverDatabase(sqlite3
*db
){
1003 int rc
; /* Return code from this routine */
1004 const char *zRecoveryDb
= ""; /* Name of "recovery" database */
1005 const char *zLAF
= "lost_and_found"; /* Name of "lost_and_found" table */
1006 int bFreelist
= 1; /* True to scan the freelist */
1007 int bRowids
= 1; /* True to restore ROWID values */
1008 sqlite3_recover
*p
= 0; /* The recovery object */
1010 p
= sqlite3_recover_init_sql(db
, "main", recoverSqlCb
, 0);
1011 sqlite3_recover_config(p
, 789, (void*)zRecoveryDb
);
1012 sqlite3_recover_config(p
, SQLITE_RECOVER_LOST_AND_FOUND
, (void*)zLAF
);
1013 sqlite3_recover_config(p
, SQLITE_RECOVER_ROWIDS
, (void*)&bRowids
);
1014 sqlite3_recover_config(p
, SQLITE_RECOVER_FREELIST_CORRUPT
,(void*)&bFreelist
);
1015 sqlite3_recover_run(p
);
1016 if( sqlite3_recover_errcode(p
)!=SQLITE_OK
){
1017 const char *zErr
= sqlite3_recover_errmsg(p
);
1018 int errCode
= sqlite3_recover_errcode(p
);
1020 printf("recovery error: %s (%d)\n", zErr
, errCode
);
1023 rc
= sqlite3_recover_finish(p
);
1024 if( eVerbosity
>0 && rc
){
1025 printf("recovery returns error code %d\n", rc
);
1033 static int runDbSql(sqlite3
*db
, const char *zSql
, unsigned int *pBtsFlags
){
1035 sqlite3_stmt
*pStmt
;
1037 while( isspace(zSql
[0]&0x7f) ) zSql
++;
1038 if( zSql
[0]==0 ) return SQLITE_OK
;
1039 if( eVerbosity
>=4 ){
1040 printf("RUNNING-SQL: [%s]\n", zSql
);
1043 (*pBtsFlags
) &= BTS_BADPRAGMA
;
1044 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
1045 if( rc
==SQLITE_OK
){
1047 while( (rc
= sqlite3_step(pStmt
))==SQLITE_ROW
){
1049 if( eVerbosity
>=4 ){
1051 for(j
=0; j
<sqlite3_column_count(pStmt
); j
++){
1052 if( j
) printf(",");
1053 switch( sqlite3_column_type(pStmt
, j
) ){
1058 case SQLITE_INTEGER
:
1059 case SQLITE_FLOAT
: {
1060 printf("%s", sqlite3_column_text(pStmt
, j
));
1064 int n
= sqlite3_column_bytes(pStmt
, j
);
1066 const unsigned char *a
;
1067 a
= (const unsigned char*)sqlite3_column_blob(pStmt
, j
);
1070 printf("%02x", a
[i
]);
1076 int n
= sqlite3_column_bytes(pStmt
, j
);
1078 const unsigned char *a
;
1079 a
= (const unsigned char*)sqlite3_column_blob(pStmt
, j
);
1091 } /* End switch() */
1095 } /* End if( eVerbosity>=5 ) */
1096 } /* End while( SQLITE_ROW */
1097 if( rc
==SQLITE_DONE
){
1098 if( (*pBtsFlags
)==BTS_SELECT
1099 && !sqlite3_stmt_isexplain(pStmt
)
1103 sqlite3_reset(pStmt
);
1104 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
1107 for(iCnt
=0; iCnt
<99999; iCnt
++){
1108 rc
= fuzz_invariant(db
, pStmt
, iCnt
, iRow
, nRow
,
1109 &bCorrupt
, eVerbosity
);
1110 if( rc
==SQLITE_DONE
) break;
1111 if( rc
!=SQLITE_ERROR
) g
.nInvariant
++;
1113 if( rc
==SQLITE_OK
){
1114 printf("invariant-check: ok\n");
1115 }else if( rc
==SQLITE_CORRUPT
){
1116 printf("invariant-check: failed due to database corruption\n");
1122 }else if( eVerbosity
>=4 ){
1123 printf("SQL-ERROR: (%d) %s\n", rc
, sqlite3_errmsg(db
));
1126 }else if( eVerbosity
>=4 ){
1127 printf("SQL-ERROR (%d): %s\n", rc
, sqlite3_errmsg(db
));
1129 } /* End if( SQLITE_OK ) */
1130 return sqlite3_finalize(pStmt
);
1133 /* Mappings into dbconfig settings for bits taken from bytes 72..75 of
1134 ** the input database.
1136 ** This should be the same as in dbsqlfuzz.c. Make sure those codes stay
1139 static const struct {
1143 } aDbConfigSettings
[] = {
1144 { 0x0001, SQLITE_DBCONFIG_ENABLE_FKEY
, "enable_fkey" },
1145 { 0x0002, SQLITE_DBCONFIG_ENABLE_TRIGGER
, "enable_trigger" },
1146 { 0x0004, SQLITE_DBCONFIG_ENABLE_VIEW
, "enable_view" },
1147 { 0x0008, SQLITE_DBCONFIG_ENABLE_QPSG
, "enable_qpsg" },
1148 { 0x0010, SQLITE_DBCONFIG_TRIGGER_EQP
, "trigger_eqp" },
1149 { 0x0020, SQLITE_DBCONFIG_DEFENSIVE
, "defensive" },
1150 { 0x0040, SQLITE_DBCONFIG_WRITABLE_SCHEMA
, "writable_schema" },
1151 { 0x0080, SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
, "legacy_alter_table" },
1152 { 0x0100, SQLITE_DBCONFIG_STMT_SCANSTATUS
, "stmt_scanstatus" },
1153 { 0x0200, SQLITE_DBCONFIG_REVERSE_SCANORDER
, "reverse_scanorder" },
1154 #ifdef SQLITE_DBCONFIG_STRICT_AGGREGATE
1155 { 0x0400, SQLITE_DBCONFIG_STRICT_AGGREGATE
, "strict_aggregate" },
1157 { 0x0800, SQLITE_DBCONFIG_DQS_DML
, "dqs_dml" },
1158 { 0x1000, SQLITE_DBCONFIG_DQS_DDL
, "dqs_ddl" },
1159 { 0x2000, SQLITE_DBCONFIG_TRUSTED_SCHEMA
, "trusted_schema" },
1162 /* Toggle a dbconfig setting
1164 static void toggleDbConfig(sqlite3
*db
, int iSetting
){
1166 sqlite3_db_config(db
, iSetting
, -1, &v
);
1168 sqlite3_db_config(db
, iSetting
, v
, 0);
1171 /* Invoke this routine to run a single test case */
1172 int runCombinedDbSqlInput(
1173 const uint8_t *aData
, /* Combined DB+SQL content */
1174 size_t nByte
, /* Size of aData in bytes */
1175 int iTimeout
, /* Use this timeout */
1176 int bScript
, /* If true, just render CLI output */
1177 int iSqlId
/* SQL identifier */
1179 int rc
; /* SQLite API return value */
1180 int iSql
; /* Index in aData[] of start of SQL */
1181 unsigned char *aDb
= 0; /* Decoded database content */
1182 int nDb
= 0; /* Size of the decoded database */
1183 int i
; /* Loop counter */
1184 int j
; /* Start of current SQL statement */
1185 char *zSql
= 0; /* SQL text to run */
1186 int nSql
; /* Bytes of SQL text */
1187 FuzzCtx cx
; /* Fuzzing context */
1188 unsigned int btsFlags
= 0; /* Parsing flags */
1189 unsigned int dbFlags
= 0; /* Flag values from db offset 72..75 */
1190 unsigned int dbOpt
= 0; /* Flag values from db offset 76..79 */
1193 if( nByte
<10 ) return 0;
1194 if( sqlite3_initialize() ) return 0;
1195 if( sqlite3_memory_used()!=0 ){
1198 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT
, &nAlloc
, &nNotUsed
, 0);
1199 fprintf(stderr
,"memory leak prior to test start:"
1200 " %lld bytes in %d allocations\n",
1201 sqlite3_memory_used(), nAlloc
);
1204 memset(&cx
, 0, sizeof(cx
));
1205 iSql
= decodeDatabase((unsigned char*)aData
, (int)nByte
, &aDb
, &nDb
);
1206 if( iSql
<0 ) return 0;
1208 dbFlags
= ((unsigned int)aDb
[72]<<24) + ((unsigned int)aDb
[73]<<16) +
1209 ((unsigned int)aDb
[74]<<8) + (unsigned int)aDb
[75];
1212 dbOpt
= ((unsigned int)aDb
[76]<<24) + ((unsigned int)aDb
[77]<<16) +
1213 ((unsigned int)aDb
[78]<<8) + (unsigned int)aDb
[79];
1215 nSql
= (int)(nByte
- iSql
);
1218 sqlite3_snprintf(sizeof(zName
),zName
,"dbsql%06d.db",iSqlId
);
1219 renderDbSqlForCLI(stdout
, zName
, aDb
, nDb
,
1220 (unsigned char*)(aData
+iSql
), nSql
);
1224 if( eVerbosity
>=3 ){
1226 "****** %d-byte input, %d-byte database, %d-byte script "
1227 "******\n", (int)nByte
, nDb
, nSql
);
1230 rc
= sqlite3_open(0, &cx
.db
);
1235 sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS
, cx
.db
, dbOpt
);
1236 for(i
=0; i
<sizeof(aDbConfigSettings
)/sizeof(aDbConfigSettings
[0]); i
++){
1237 if( dbFlags
& aDbConfigSettings
[i
].mask
){
1238 toggleDbConfig(cx
.db
, aDbConfigSettings
[i
].iSetting
);
1242 sqlite3_exec(cx
.db
, "PRAGMA vdbe_debug=ON", 0, 0, 0);
1245 /* Invoke the progress handler frequently to check to see if we
1246 ** are taking too long. The progress handler will return true
1247 ** (which will block further processing) if more than giTimeout seconds have
1248 ** elapsed since the start of the test.
1250 cx
.iLastCb
= timeOfDay();
1251 cx
.iCutoffTime
= cx
.iLastCb
+ (iTimeout
<giTimeout
? iTimeout
: giTimeout
);
1252 cx
.mxCb
= mxProgressCb
;
1253 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1254 sqlite3_progress_handler(cx
.db
, 10, progress_handler
, (void*)&cx
);
1257 /* Set a limit on the maximum size of a prepared statement, and the
1258 ** maximum length of a string or blob */
1259 if( vdbeOpLimit
>0 ){
1260 sqlite3_limit(cx
.db
, SQLITE_LIMIT_VDBE_OP
, vdbeOpLimit
);
1262 if( lengthLimit
>0 ){
1263 sqlite3_limit(cx
.db
, SQLITE_LIMIT_LENGTH
, lengthLimit
);
1266 sqlite3_limit(cx
.db
, SQLITE_LIMIT_EXPR_DEPTH
, depthLimit
);
1268 sqlite3_limit(cx
.db
, SQLITE_LIMIT_LIKE_PATTERN_LENGTH
, 100);
1269 sqlite3_hard_heap_limit64(heapLimit
);
1271 if( nDb
>=20 && aDb
[18]==2 && aDb
[19]==2 ){
1272 aDb
[18] = aDb
[19] = 1;
1274 rc
= sqlite3_deserialize(cx
.db
, "main", aDb
, nDb
, nDb
,
1275 SQLITE_DESERIALIZE_RESIZEABLE
|
1276 SQLITE_DESERIALIZE_FREEONCLOSE
);
1278 fprintf(stderr
, "sqlite3_deserialize() failed with %d\n", rc
);
1279 goto testrun_finished
;
1282 sqlite3_int64 x
= maxDbSize
;
1283 sqlite3_file_control(cx
.db
, "main", SQLITE_FCNTL_SIZE_LIMIT
, &x
);
1286 /* For high debugging levels, turn on debug mode */
1287 if( eVerbosity
>=5 ){
1288 sqlite3_exec(cx
.db
, "PRAGMA vdbe_debug=ON;", 0, 0, 0);
1291 /* Block debug pragmas and ATTACH/DETACH. But wait until after
1292 ** deserialize to do this because deserialize depends on ATTACH */
1293 sqlite3_set_authorizer(cx
.db
, block_troublesome_sql
, &btsFlags
);
1295 /* Add the vt02 virtual table */
1296 sqlite3_vt02_init(cx
.db
, 0, 0);
1298 /* Add support for sqlite_dbdata and sqlite_dbptr virtual tables used
1299 ** by the recovery API */
1300 sqlite3_dbdata_init(cx
.db
, 0, 0);
1302 /* Consistent PRNG seed */
1303 #ifdef SQLITE_TESTCTRL_PRNG_SEED
1304 sqlite3_table_column_metadata(cx
.db
, 0, "x", 0, 0, 0, 0, 0, 0);
1305 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED
, 1, cx
.db
);
1307 sqlite3_randomness(0,0);
1310 /* Run recovery on the initial database, just to make sure recovery
1313 recoverDatabase(cx
.db
);
1316 zSql
= sqlite3_malloc( nSql
+ 1 );
1318 fprintf(stderr
, "Out of memory!\n");
1320 memcpy(zSql
, aData
+iSql
, nSql
);
1322 for(i
=j
=0; zSql
[i
]; i
++){
1324 char cSaved
= zSql
[i
+1];
1326 if( sqlite3_complete(zSql
+j
) ){
1327 rc
= runDbSql(cx
.db
, zSql
+j
, &btsFlags
);
1331 if( rc
==SQLITE_INTERRUPT
|| progress_handler(&cx
) ){
1332 goto testrun_finished
;
1337 runDbSql(cx
.db
, zSql
+j
, &btsFlags
);
1342 rc
= sqlite3_close(cx
.db
);
1343 if( rc
!=SQLITE_OK
){
1344 fprintf(stdout
, "sqlite3_close() returns %d\n", rc
);
1346 if( eVerbosity
>=2 && !bScript
){
1347 fprintf(stdout
, "Peak memory usages: %f MB\n",
1348 sqlite3_memory_highwater(1) / 1000000.0);
1350 if( sqlite3_memory_used()!=0 ){
1353 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT
, &nAlloc
, &nNotUsed
, 0);
1354 fprintf(stderr
,"Memory leak: %lld bytes in %d allocations\n",
1355 sqlite3_memory_used(), nAlloc
);
1358 sqlite3_hard_heap_limit64(0);
1359 sqlite3_soft_heap_limit64(0);
1364 ** END of the dbsqlfuzz code
1365 ***************************************************************************/
1367 /* Look at a SQL text and try to determine if it begins with a database
1368 ** description, such as would be found in a dbsqlfuzz test case. Return
1369 ** true if this does appear to be a dbsqlfuzz test case and false otherwise.
1371 static int isDbSql(unsigned char *a
, int n
){
1372 unsigned char buf
[12];
1374 if( n
>4 && memcmp(a
,"\n--\n",4)==0 ) return 1;
1375 while( n
>0 && isspace(a
[0]) ){ a
++; n
--; }
1376 for(i
=0; n
>0 && i
<8; n
--, a
++){
1377 if( isxdigit(a
[0]) ) buf
[i
++] = a
[0];
1379 if( i
==8 && memcmp(buf
,"53514c69",8)==0 ) return 1;
1383 /* Implementation of the isdbsql(TEXT) SQL function.
1385 static void isDbSqlFunc(
1386 sqlite3_context
*context
,
1388 sqlite3_value
**argv
1390 int n
= sqlite3_value_bytes(argv
[0]);
1391 unsigned char *a
= (unsigned char*)sqlite3_value_blob(argv
[0]);
1392 sqlite3_result_int(context
, a
!=0 && n
>0 && isDbSql(a
,n
));
1395 /* Methods for the VHandle object
1397 static int inmemClose(sqlite3_file
*pFile
){
1398 VHandle
*p
= (VHandle
*)pFile
;
1399 VFile
*pVFile
= p
->pVFile
;
1401 if( pVFile
->nRef
==0 && pVFile
->zFilename
==0 ){
1408 static int inmemRead(
1409 sqlite3_file
*pFile
, /* Read from this open file */
1410 void *pData
, /* Store content in this buffer */
1411 int iAmt
, /* Bytes of content */
1412 sqlite3_int64 iOfst
/* Start reading here */
1414 VHandle
*pHandle
= (VHandle
*)pFile
;
1415 VFile
*pVFile
= pHandle
->pVFile
;
1416 if( iOfst
<0 || iOfst
>=pVFile
->sz
){
1417 memset(pData
, 0, iAmt
);
1418 return SQLITE_IOERR_SHORT_READ
;
1420 if( iOfst
+iAmt
>pVFile
->sz
){
1421 memset(pData
, 0, iAmt
);
1422 iAmt
= (int)(pVFile
->sz
- iOfst
);
1423 memcpy(pData
, pVFile
->a
+ iOfst
, iAmt
);
1424 return SQLITE_IOERR_SHORT_READ
;
1426 memcpy(pData
, pVFile
->a
+ iOfst
, iAmt
);
1429 static int inmemWrite(
1430 sqlite3_file
*pFile
, /* Write to this file */
1431 const void *pData
, /* Content to write */
1432 int iAmt
, /* bytes to write */
1433 sqlite3_int64 iOfst
/* Start writing here */
1435 VHandle
*pHandle
= (VHandle
*)pFile
;
1436 VFile
*pVFile
= pHandle
->pVFile
;
1437 if( iOfst
+iAmt
> pVFile
->sz
){
1438 if( iOfst
+iAmt
>= MX_FILE_SZ
){
1441 pVFile
->a
= safe_realloc(pVFile
->a
, (int)(iOfst
+iAmt
));
1442 if( iOfst
> pVFile
->sz
){
1443 memset(pVFile
->a
+ pVFile
->sz
, 0, (int)(iOfst
- pVFile
->sz
));
1445 pVFile
->sz
= (int)(iOfst
+ iAmt
);
1447 memcpy(pVFile
->a
+ iOfst
, pData
, iAmt
);
1450 static int inmemTruncate(sqlite3_file
*pFile
, sqlite3_int64 iSize
){
1451 VHandle
*pHandle
= (VHandle
*)pFile
;
1452 VFile
*pVFile
= pHandle
->pVFile
;
1453 if( pVFile
->sz
>iSize
&& iSize
>=0 ) pVFile
->sz
= (int)iSize
;
1456 static int inmemSync(sqlite3_file
*pFile
, int flags
){
1459 static int inmemFileSize(sqlite3_file
*pFile
, sqlite3_int64
*pSize
){
1460 *pSize
= ((VHandle
*)pFile
)->pVFile
->sz
;
1463 static int inmemLock(sqlite3_file
*pFile
, int type
){
1466 static int inmemUnlock(sqlite3_file
*pFile
, int type
){
1469 static int inmemCheckReservedLock(sqlite3_file
*pFile
, int *pOut
){
1473 static int inmemFileControl(sqlite3_file
*pFile
, int op
, void *pArg
){
1474 return SQLITE_NOTFOUND
;
1476 static int inmemSectorSize(sqlite3_file
*pFile
){
1479 static int inmemDeviceCharacteristics(sqlite3_file
*pFile
){
1481 SQLITE_IOCAP_SAFE_APPEND
|
1482 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
|
1483 SQLITE_IOCAP_POWERSAFE_OVERWRITE
;
1487 /* Method table for VHandle
1489 static sqlite3_io_methods VHandleMethods
= {
1491 /* xClose */ inmemClose
,
1492 /* xRead */ inmemRead
,
1493 /* xWrite */ inmemWrite
,
1494 /* xTruncate */ inmemTruncate
,
1495 /* xSync */ inmemSync
,
1496 /* xFileSize */ inmemFileSize
,
1497 /* xLock */ inmemLock
,
1498 /* xUnlock */ inmemUnlock
,
1499 /* xCheck... */ inmemCheckReservedLock
,
1500 /* xFileCtrl */ inmemFileControl
,
1501 /* xSectorSz */ inmemSectorSize
,
1502 /* xDevchar */ inmemDeviceCharacteristics
,
1505 /* xShmBarrier */ 0,
1512 ** Open a new file in the inmem VFS. All files are anonymous and are
1515 static int inmemOpen(
1517 const char *zFilename
,
1518 sqlite3_file
*pFile
,
1522 VFile
*pVFile
= createVFile(zFilename
, 0, (unsigned char*)"");
1523 VHandle
*pHandle
= (VHandle
*)pFile
;
1527 pHandle
->pVFile
= pVFile
;
1529 pFile
->pMethods
= &VHandleMethods
;
1530 if( pOutFlags
) *pOutFlags
= openFlags
;
1535 ** Delete a file by name
1537 static int inmemDelete(
1539 const char *zFilename
,
1542 VFile
*pVFile
= findVFile(zFilename
);
1543 if( pVFile
==0 ) return SQLITE_OK
;
1544 if( pVFile
->nRef
==0 ){
1545 free(pVFile
->zFilename
);
1546 pVFile
->zFilename
= 0;
1552 return SQLITE_IOERR_DELETE
;
1555 /* Check for the existance of a file
1557 static int inmemAccess(
1559 const char *zFilename
,
1563 VFile
*pVFile
= findVFile(zFilename
);
1564 *pResOut
= pVFile
!=0;
1568 /* Get the canonical pathname for a file
1570 static int inmemFullPathname(
1572 const char *zFilename
,
1576 sqlite3_snprintf(nOut
, zOut
, "%s", zFilename
);
1580 /* Always use the same random see, for repeatability.
1582 static int inmemRandomness(sqlite3_vfs
*NotUsed
, int nBuf
, char *zBuf
){
1583 memset(zBuf
, 0, nBuf
);
1584 memcpy(zBuf
, &g
.uRandom
, nBuf
<sizeof(g
.uRandom
) ? nBuf
: sizeof(g
.uRandom
));
1589 ** Register the VFS that reads from the g.aFile[] set of files.
1591 static void inmemVfsRegister(int makeDefault
){
1592 static sqlite3_vfs inmemVfs
;
1593 sqlite3_vfs
*pDefault
= sqlite3_vfs_find(0);
1594 inmemVfs
.iVersion
= 3;
1595 inmemVfs
.szOsFile
= sizeof(VHandle
);
1596 inmemVfs
.mxPathname
= 200;
1597 inmemVfs
.zName
= "inmem";
1598 inmemVfs
.xOpen
= inmemOpen
;
1599 inmemVfs
.xDelete
= inmemDelete
;
1600 inmemVfs
.xAccess
= inmemAccess
;
1601 inmemVfs
.xFullPathname
= inmemFullPathname
;
1602 inmemVfs
.xRandomness
= inmemRandomness
;
1603 inmemVfs
.xSleep
= pDefault
->xSleep
;
1604 inmemVfs
.xCurrentTimeInt64
= pDefault
->xCurrentTimeInt64
;
1605 sqlite3_vfs_register(&inmemVfs
, makeDefault
);
1609 ** Allowed values for the runFlags parameter to runSql()
1611 #define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */
1612 #define SQL_OUTPUT 0x0002 /* Show the SQL output */
1615 ** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not
1616 ** stop if an error is encountered.
1618 static void runSql(sqlite3
*db
, const char *zSql
, unsigned runFlags
){
1620 sqlite3_stmt
*pStmt
;
1622 while( zSql
&& zSql
[0] ){
1625 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zMore
);
1626 if( zMore
==zSql
) break;
1627 if( runFlags
& SQL_TRACE
){
1628 const char *z
= zSql
;
1630 while( z
<zMore
&& ISSPACE(z
[0]) ) z
++;
1631 n
= (int)(zMore
- z
);
1632 while( n
>0 && ISSPACE(z
[n
-1]) ) n
--;
1635 printf("TRACE: %.*s (error: %s)\n", n
, z
, sqlite3_errmsg(db
));
1637 printf("TRACE: %.*s\n", n
, z
);
1642 if( (runFlags
& SQL_OUTPUT
)==0 ){
1643 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){}
1646 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
1649 nCol
= sqlite3_column_count(pStmt
);
1651 printf("--------------------------------------------\n");
1653 for(i
=0; i
<nCol
; i
++){
1654 int eType
= sqlite3_column_type(pStmt
,i
);
1655 printf("%s = ", sqlite3_column_name(pStmt
,i
));
1661 case SQLITE_INTEGER
: {
1662 printf("INT %s\n", sqlite3_column_text(pStmt
,i
));
1665 case SQLITE_FLOAT
: {
1666 printf("FLOAT %s\n", sqlite3_column_text(pStmt
,i
));
1670 printf("TEXT [%s]\n", sqlite3_column_text(pStmt
,i
));
1674 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt
,i
));
1681 sqlite3_finalize(pStmt
);
1687 ** Rebuild the database file.
1689 ** (1) Remove duplicate entries
1690 ** (2) Put all entries in order
1693 static void rebuild_database(sqlite3
*db
, int dbSqlOnly
){
1696 zSql
= sqlite3_mprintf(
1698 "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
1700 "INSERT INTO db(dbid, dbcontent) "
1701 " SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
1703 "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql %s;\n"
1704 "DELETE FROM xsql;\n"
1705 "INSERT INTO xsql(sqlid,sqltext) "
1706 " SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
1709 "PRAGMA page_size=1024;\n"
1711 dbSqlOnly
? " WHERE isdbsql(sqltext)" : ""
1713 rc
= sqlite3_exec(db
, zSql
, 0, 0, 0);
1715 if( rc
) fatalError("cannot rebuild: %s", sqlite3_errmsg(db
));
1719 ** Return the value of a hexadecimal digit. Return -1 if the input
1720 ** is not a hex digit.
1722 static int hexDigitValue(char c
){
1723 if( c
>='0' && c
<='9' ) return c
- '0';
1724 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
1725 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
1730 ** Interpret zArg as an integer value, possibly with suffixes.
1732 static int integerValue(const char *zArg
){
1733 sqlite3_int64 v
= 0;
1734 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
1736 { "MiB", 1024*1024 },
1737 { "GiB", 1024*1024*1024 },
1740 { "GB", 1000000000 },
1743 { "G", 1000000000 },
1750 }else if( zArg
[0]=='+' ){
1753 if( zArg
[0]=='0' && zArg
[1]=='x' ){
1756 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
1761 while( ISDIGIT(zArg
[0]) ){
1762 v
= v
*10 + zArg
[0] - '0';
1766 for(i
=0; i
<sizeof(aMult
)/sizeof(aMult
[0]); i
++){
1767 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
1768 v
*= aMult
[i
].iMult
;
1772 if( v
>0x7fffffff ) fatalError("parameter too large - max 2147483648");
1773 return (int)(isNeg
? -v
: v
);
1777 ** Return the number of "v" characters in a string. Return 0 if there
1778 ** are any characters in the string other than "v".
1780 static int numberOfVChar(const char *z
){
1782 while( z
[0] && z
[0]=='v' ){
1786 return z
[0]==0 ? N
: 0;
1790 ** Print sketchy documentation for this utility program
1792 static void showHelp(void){
1793 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g
.zArgv0
);
1795 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
1796 "each database, checking for crashes and memory leaks.\n"
1798 " --cell-size-check Set the PRAGMA cell_size_check=ON\n"
1799 " --dbid N Use only the database where dbid=N\n"
1800 " --export-db DIR Write databases to files(s) in DIR. Works with --dbid\n"
1801 " --export-sql DIR Write SQL to file(s) in DIR. Also works with --sqlid\n"
1802 " --help Show this help text\n"
1803 " --info Show information about SOURCE-DB w/o running tests\n"
1804 " --limit-depth N Limit expression depth to N. Default: 500\n"
1805 " --limit-heap N Limit heap memory to N. Default: 100M\n"
1806 " --limit-mem N Limit memory used by test SQLite instance to N bytes\n"
1807 " --limit-vdbe Panic if any test runs for more than 100,000 cycles\n"
1808 " --load-sql FILE.. Load SQL scripts fron files into SOURCE-DB\n"
1809 " --load-db FILE.. Load template databases from files into SOURCE_DB\n"
1810 " --load-dbsql FILE.. Load dbsqlfuzz outputs into the xsql table\n"
1811 " ^^^^------ Use \"-\" for FILE to read filenames from stdin\n"
1812 " -m TEXT Add a description to the database\n"
1813 " --native-vfs Use the native VFS for initially empty database files\n"
1814 " --native-malloc Turn off MEMSYS3/5 and Lookaside\n"
1815 " --no-recover Do not run recovery on dbsqlfuzz databases\n"
1816 " --oss-fuzz Enable OSS-FUZZ testing\n"
1817 " --prng-seed N Seed value for the PRGN inside of SQLite\n"
1818 " -q|--quiet Reduced output\n"
1819 " --rebuild Rebuild and vacuum the database file\n"
1820 " --result-trace Show the results of each SQL command\n"
1821 " --script Output CLI script instead of running tests\n"
1822 " --skip N Skip the first N test cases\n"
1823 " --spinner Use a spinner to show progress\n"
1824 " --sqlid N Use only SQL where sqlid=N\n"
1825 " --timeout N Maximum time for any one test in N millseconds\n"
1826 " -v|--verbose Increased output. Repeat for more output.\n"
1827 " --vdbe-debug Activate VDBE debugging.\n"
1828 " --wait N Wait N seconds before continuing - useful for\n"
1829 " attaching an MSVC debugging.\n"
1833 int main(int argc
, char **argv
){
1834 sqlite3_int64 iBegin
; /* Start time of this program */
1835 int quietFlag
= 0; /* True if --quiet or -q */
1836 int verboseFlag
= 0; /* True if --verbose or -v */
1837 char *zInsSql
= 0; /* SQL statement for --load-db or --load-sql */
1838 int iFirstInsArg
= 0; /* First argv[] for --load-db or --load-sql */
1839 sqlite3
*db
= 0; /* The open database connection */
1840 sqlite3_stmt
*pStmt
; /* A prepared statement */
1841 int rc
; /* Result code from SQLite interface calls */
1842 Blob
*pSql
; /* For looping over SQL scripts */
1843 Blob
*pDb
; /* For looping over template databases */
1844 int i
; /* Loop index for the argv[] loop */
1845 int dbSqlOnly
= 0; /* Only use scripts that are dbsqlfuzz */
1846 int onlySqlid
= -1; /* --sqlid */
1847 int onlyDbid
= -1; /* --dbid */
1848 int nativeFlag
= 0; /* --native-vfs */
1849 int rebuildFlag
= 0; /* --rebuild */
1850 int vdbeLimitFlag
= 0; /* --limit-vdbe */
1851 int infoFlag
= 0; /* --info */
1852 int nSkip
= 0; /* --skip */
1853 int bScript
= 0; /* --script */
1854 int bSpinner
= 0; /* True for --spinner */
1855 int timeoutTest
= 0; /* undocumented --timeout-test flag */
1856 int runFlags
= 0; /* Flags sent to runSql() */
1857 char *zMsg
= 0; /* Add this message */
1858 int nSrcDb
= 0; /* Number of source databases */
1859 char **azSrcDb
= 0; /* Array of source database names */
1860 int iSrcDb
; /* Loop over all source databases */
1861 int nTest
= 0; /* Total number of tests performed */
1862 char *zDbName
= ""; /* Appreviated name of a source database */
1863 const char *zFailCode
= 0; /* Value of the TEST_FAILURE env variable */
1864 int cellSzCkFlag
= 0; /* --cell-size-check */
1865 int sqlFuzz
= 0; /* True for SQL fuzz. False for DB fuzz */
1866 int iTimeout
= 120000; /* Default 120-second timeout */
1867 int nMem
= 0; /* Memory limit override */
1868 int nMemThisDb
= 0; /* Memory limit set by the CONFIG table */
1869 char *zExpDb
= 0; /* Write Databases to files in this directory */
1870 char *zExpSql
= 0; /* Write SQL to files in this directory */
1871 void *pHeap
= 0; /* Heap for use by SQLite */
1872 int ossFuzz
= 0; /* enable OSS-FUZZ testing */
1873 int ossFuzzThisDb
= 0; /* ossFuzz value for this particular database */
1874 int nativeMalloc
= 0; /* Turn off MEMSYS3/5 and lookaside if true */
1875 sqlite3_vfs
*pDfltVfs
; /* The default VFS */
1876 int openFlags4Data
; /* Flags for sqlite3_open_v2() */
1877 int bTimer
= 0; /* Show elapse time for each test */
1878 int nV
; /* How much to increase verbosity with -vvvv */
1879 sqlite3_int64 tmStart
; /* Start of each test */
1881 sqlite3_config(SQLITE_CONFIG_URI
,1);
1882 registerOomSimulator();
1883 sqlite3_initialize();
1884 iBegin
= timeOfDay();
1886 signal(SIGALRM
, signalHandler
);
1887 signal(SIGSEGV
, signalHandler
);
1888 signal(SIGABRT
, signalHandler
);
1891 openFlags4Data
= SQLITE_OPEN_READONLY
;
1892 zFailCode
= getenv("TEST_FAILURE");
1893 pDfltVfs
= sqlite3_vfs_find(0);
1894 inmemVfsRegister(1);
1895 for(i
=1; i
<argc
; i
++){
1896 const char *z
= argv
[i
];
1899 if( z
[0]=='-' ) z
++;
1900 if( strcmp(z
,"cell-size-check")==0 ){
1903 if( strcmp(z
,"dbid")==0 ){
1904 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1905 onlyDbid
= integerValue(argv
[++i
]);
1907 if( strcmp(z
,"export-db")==0 ){
1908 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1911 if( strcmp(z
,"export-sql")==0 || strcmp(z
,"export-dbsql")==0 ){
1912 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1913 zExpSql
= argv
[++i
];
1915 if( strcmp(z
,"help")==0 ){
1919 if( strcmp(z
,"info")==0 ){
1922 if( strcmp(z
,"limit-depth")==0 ){
1923 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1924 depthLimit
= integerValue(argv
[++i
]);
1926 if( strcmp(z
,"limit-heap")==0 ){
1927 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1928 heapLimit
= integerValue(argv
[++i
]);
1930 if( strcmp(z
,"limit-mem")==0 ){
1931 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1932 nMem
= integerValue(argv
[++i
]);
1934 if( strcmp(z
,"limit-vdbe")==0 ){
1937 if( strcmp(z
,"load-sql")==0 ){
1938 zInsSql
= "INSERT INTO xsql(sqltext)"
1939 "VALUES(CAST(readtextfile(?1) AS text))";
1941 openFlags4Data
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
1944 if( strcmp(z
,"load-db")==0 ){
1945 zInsSql
= "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
1947 openFlags4Data
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
1950 if( strcmp(z
,"load-dbsql")==0 ){
1951 zInsSql
= "INSERT INTO xsql(sqltext)"
1952 "VALUES(readfile(?1))";
1954 openFlags4Data
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
1958 if( strcmp(z
,"m")==0 ){
1959 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1961 openFlags4Data
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
1963 if( strcmp(z
,"native-malloc")==0 ){
1966 if( strcmp(z
,"native-vfs")==0 ){
1969 if( strcmp(z
,"no-recover")==0 ){
1972 if( strcmp(z
,"oss-fuzz")==0 ){
1975 if( strcmp(z
,"prng-seed")==0 ){
1976 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1977 g
.uRandom
= atoi(argv
[++i
]);
1979 if( strcmp(z
,"quiet")==0 || strcmp(z
,"q")==0 ){
1984 if( strcmp(z
,"rebuild")==0 ){
1986 openFlags4Data
= SQLITE_OPEN_READWRITE
;
1988 if( strcmp(z
,"result-trace")==0 ){
1989 runFlags
|= SQL_OUTPUT
;
1991 if( strcmp(z
,"script")==0 ){
1994 if( strcmp(z
,"skip")==0 ){
1995 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
1996 nSkip
= atoi(argv
[++i
]);
1998 if( strcmp(z
,"spinner")==0 ){
2001 if( strcmp(z
,"timer")==0 ){
2004 if( strcmp(z
,"sqlid")==0 ){
2005 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
2006 onlySqlid
= integerValue(argv
[++i
]);
2008 if( strcmp(z
,"timeout")==0 ){
2009 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
2010 iTimeout
= integerValue(argv
[++i
]);
2012 if( strcmp(z
,"timeout-test")==0 ){
2015 fatalError("timeout is not available on non-unix systems");
2018 if( strcmp(z
,"vdbe-debug")==0 ){
2021 if( strcmp(z
,"verbose")==0 ){
2025 if( verboseFlag
>2 ) runFlags
|= SQL_TRACE
;
2027 if( (nV
= numberOfVChar(z
))>=1 ){
2031 if( verboseFlag
>2 ) runFlags
|= SQL_TRACE
;
2033 if( strcmp(z
,"version")==0 ){
2036 printf("SQLite %s %s (%d-bit)\n",
2037 sqlite3_libversion(), sqlite3_sourceid(),
2038 8*(int)sizeof(char*));
2039 for(ii
=0; (zz
= sqlite3_compileoption_get(ii
))!=0; ii
++){
2044 if( strcmp(z
,"wait")==0 ){
2046 if( i
>=argc
-1 ) fatalError("missing arguments on %s", argv
[i
]);
2047 iDelay
= integerValue(argv
[++i
]);
2048 printf("Waiting %d seconds:", iDelay
);
2050 while( 1 /*exit-by-break*/ ){
2051 sqlite3_sleep(1000);
2053 if( iDelay
<=0 ) break;
2054 printf(" %d", iDelay
);
2060 if( strcmp(z
,"is-dbsql")==0 ){
2062 for(i
++; i
<argc
; i
++){
2064 char *aData
= readFile(argv
[i
], &nData
);
2065 printf("%d %s\n", isDbSql((unsigned char*)aData
,nData
), argv
[i
]);
2066 sqlite3_free(aData
);
2071 fatalError("unknown option: %s", argv
[i
]);
2075 azSrcDb
= safe_realloc(azSrcDb
, nSrcDb
*sizeof(azSrcDb
[0]));
2076 azSrcDb
[nSrcDb
-1] = argv
[i
];
2079 if( nSrcDb
==0 ) fatalError("no source database specified");
2082 fatalError("cannot change the description of more than one database");
2085 fatalError("cannot import into more than one database");
2089 /* Process each source database separately */
2090 for(iSrcDb
=0; iSrcDb
<nSrcDb
; iSrcDb
++){
2093 g
.zDbFile
= azSrcDb
[iSrcDb
];
2094 rc
= sqlite3_open_v2(azSrcDb
[iSrcDb
], &db
,
2095 openFlags4Data
, pDfltVfs
->zName
);
2096 if( rc
==SQLITE_OK
){
2097 rc
= sqlite3_exec(db
, "SELECT count(*) FROM sqlite_schema", 0, 0, 0);
2101 zRawData
= readFile(azSrcDb
[iSrcDb
], &nRawData
);
2103 fatalError("input file \"%s\" is not recognized\n", azSrcDb
[iSrcDb
]);
2105 sqlite3_open(":memory:", &db
);
2108 /* Print the description, if there is one */
2111 zDbName
= azSrcDb
[iSrcDb
];
2112 i
= (int)strlen(zDbName
) - 1;
2113 while( i
>0 && zDbName
[i
-1]!='/' && zDbName
[i
-1]!='\\' ){ i
--; }
2115 sqlite3_prepare_v2(db
, "SELECT msg FROM readme", -1, &pStmt
, 0);
2116 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
2117 printf("%s: %s", zDbName
, sqlite3_column_text(pStmt
,0));
2119 printf("%s: (empty \"readme\")", zDbName
);
2121 sqlite3_finalize(pStmt
);
2122 sqlite3_prepare_v2(db
, "SELECT count(*) FROM db", -1, &pStmt
, 0);
2124 && sqlite3_step(pStmt
)==SQLITE_ROW
2125 && (n
= sqlite3_column_int(pStmt
,0))>0
2127 printf(" - %d DBs", n
);
2129 sqlite3_finalize(pStmt
);
2130 sqlite3_prepare_v2(db
, "SELECT count(*) FROM xsql", -1, &pStmt
, 0);
2132 && sqlite3_step(pStmt
)==SQLITE_ROW
2133 && (n
= sqlite3_column_int(pStmt
,0))>0
2135 printf(" - %d scripts", n
);
2137 sqlite3_finalize(pStmt
);
2140 sqlite3_free(zRawData
);
2144 rc
= sqlite3_exec(db
,
2145 "CREATE TABLE IF NOT EXISTS db(\n"
2146 " dbid INTEGER PRIMARY KEY, -- database id\n"
2147 " dbcontent BLOB -- database disk file image\n"
2149 "CREATE TABLE IF NOT EXISTS xsql(\n"
2150 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n"
2151 " sqltext TEXT -- Text of SQL statements to run\n"
2153 "CREATE TABLE IF NOT EXISTS readme(\n"
2154 " msg TEXT -- Human-readable description of this file\n"
2156 if( rc
) fatalError("cannot create schema: %s", sqlite3_errmsg(db
));
2159 zSql
= sqlite3_mprintf(
2160 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg
);
2161 rc
= sqlite3_exec(db
, zSql
, 0, 0, 0);
2163 if( rc
) fatalError("cannot change description: %s", sqlite3_errmsg(db
));
2166 zInsSql
= "INSERT INTO xsql(sqltext) VALUES(?1)";
2167 rc
= sqlite3_prepare_v2(db
, zInsSql
, -1, &pStmt
, 0);
2168 if( rc
) fatalError("cannot prepare statement [%s]: %s",
2169 zInsSql
, sqlite3_errmsg(db
));
2170 sqlite3_bind_text(pStmt
, 1, zRawData
, nRawData
, SQLITE_STATIC
);
2171 sqlite3_step(pStmt
);
2172 rc
= sqlite3_reset(pStmt
);
2173 if( rc
) fatalError("insert failed for %s", argv
[i
]);
2174 sqlite3_finalize(pStmt
);
2175 rebuild_database(db
, dbSqlOnly
);
2177 sqlite3_free(zRawData
);
2180 ossFuzzThisDb
= ossFuzz
;
2182 /* If the CONFIG(name,value) table exists, read db-specific settings
2183 ** from that table */
2184 if( sqlite3_table_column_metadata(db
,0,"config",0,0,0,0,0,0)==SQLITE_OK
){
2185 rc
= sqlite3_prepare_v2(db
, "SELECT name, value FROM config",
2187 if( rc
) fatalError("cannot prepare query of CONFIG table: %s",
2188 sqlite3_errmsg(db
));
2189 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
2190 const char *zName
= (const char *)sqlite3_column_text(pStmt
,0);
2191 if( zName
==0 ) continue;
2192 if( strcmp(zName
, "oss-fuzz")==0 ){
2193 ossFuzzThisDb
= sqlite3_column_int(pStmt
,1);
2194 if( verboseFlag
>1 ) printf("Config: oss-fuzz=%d\n", ossFuzzThisDb
);
2196 if( strcmp(zName
, "limit-mem")==0 ){
2197 nMemThisDb
= sqlite3_column_int(pStmt
,1);
2198 if( verboseFlag
>1 ) printf("Config: limit-mem=%d\n", nMemThisDb
);
2201 sqlite3_finalize(pStmt
);
2205 sqlite3_create_function(db
, "readfile", 1, SQLITE_UTF8
, 0,
2206 readfileFunc
, 0, 0);
2207 sqlite3_create_function(db
, "readtextfile", 1, SQLITE_UTF8
, 0,
2208 readtextfileFunc
, 0, 0);
2209 sqlite3_create_function(db
, "isdbsql", 1, SQLITE_UTF8
, 0,
2211 rc
= sqlite3_prepare_v2(db
, zInsSql
, -1, &pStmt
, 0);
2212 if( rc
) fatalError("cannot prepare statement [%s]: %s",
2213 zInsSql
, sqlite3_errmsg(db
));
2214 rc
= sqlite3_exec(db
, "BEGIN", 0, 0, 0);
2215 if( rc
) fatalError("cannot start a transaction");
2216 for(i
=iFirstInsArg
; i
<argc
; i
++){
2217 if( strcmp(argv
[i
],"-")==0 ){
2218 /* A filename of "-" means read multiple filenames from stdin */
2220 while( rc
==0 && fgets(zLine
,sizeof(zLine
),stdin
)!=0 ){
2221 size_t kk
= strlen(zLine
);
2222 while( kk
>0 && zLine
[kk
-1]<=' ' ) kk
--;
2223 sqlite3_bind_text(pStmt
, 1, zLine
, (int)kk
, SQLITE_STATIC
);
2224 if( verboseFlag
>1 ) printf("loading %.*s\n", (int)kk
, zLine
);
2225 sqlite3_step(pStmt
);
2226 rc
= sqlite3_reset(pStmt
);
2227 if( rc
) fatalError("insert failed for %s", zLine
);
2230 sqlite3_bind_text(pStmt
, 1, argv
[i
], -1, SQLITE_STATIC
);
2231 if( verboseFlag
>1 ) printf("loading %s\n", argv
[i
]);
2232 sqlite3_step(pStmt
);
2233 rc
= sqlite3_reset(pStmt
);
2234 if( rc
) fatalError("insert failed for %s", argv
[i
]);
2237 sqlite3_finalize(pStmt
);
2238 rc
= sqlite3_exec(db
, "COMMIT", 0, 0, 0);
2239 if( rc
) fatalError("cannot commit the transaction: %s",
2240 sqlite3_errmsg(db
));
2241 rebuild_database(db
, dbSqlOnly
);
2245 rc
= sqlite3_exec(db
, "PRAGMA query_only=1;", 0, 0, 0);
2246 if( rc
) fatalError("cannot set database to query-only");
2247 if( zExpDb
!=0 || zExpSql
!=0 ){
2248 sqlite3_create_function(db
, "writefile", 2, SQLITE_UTF8
, 0,
2249 writefileFunc
, 0, 0);
2252 "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
2253 " dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
2254 " FROM db WHERE ?2<0 OR dbid=?2;";
2255 rc
= sqlite3_prepare_v2(db
, zExDb
, -1, &pStmt
, 0);
2256 if( rc
) fatalError("cannot prepare statement [%s]: %s",
2257 zExDb
, sqlite3_errmsg(db
));
2258 sqlite3_bind_text64(pStmt
, 1, zExpDb
, strlen(zExpDb
),
2259 SQLITE_STATIC
, SQLITE_UTF8
);
2260 sqlite3_bind_int(pStmt
, 2, onlyDbid
);
2261 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
2262 printf("write db-%d (%d bytes) into %s\n",
2263 sqlite3_column_int(pStmt
,1),
2264 sqlite3_column_int(pStmt
,3),
2265 sqlite3_column_text(pStmt
,2));
2267 sqlite3_finalize(pStmt
);
2270 const char *zExSql
=
2271 "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
2272 " sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
2273 " FROM xsql WHERE ?2<0 OR sqlid=?2;";
2274 rc
= sqlite3_prepare_v2(db
, zExSql
, -1, &pStmt
, 0);
2275 if( rc
) fatalError("cannot prepare statement [%s]: %s",
2276 zExSql
, sqlite3_errmsg(db
));
2277 sqlite3_bind_text64(pStmt
, 1, zExpSql
, strlen(zExpSql
),
2278 SQLITE_STATIC
, SQLITE_UTF8
);
2279 sqlite3_bind_int(pStmt
, 2, onlySqlid
);
2280 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
2281 printf("write sql-%d (%d bytes) into %s\n",
2282 sqlite3_column_int(pStmt
,1),
2283 sqlite3_column_int(pStmt
,3),
2284 sqlite3_column_text(pStmt
,2));
2286 sqlite3_finalize(pStmt
);
2292 /* Load all SQL script content and all initial database images from the
2295 blobListLoadFromDb(db
, "SELECT sqlid, sqltext FROM xsql", onlySqlid
,
2296 &g
.nSql
, &g
.pFirstSql
);
2297 if( g
.nSql
==0 ) fatalError("need at least one SQL script");
2298 blobListLoadFromDb(db
, "SELECT dbid, dbcontent FROM db", onlyDbid
,
2299 &g
.nDb
, &g
.pFirstDb
);
2301 g
.pFirstDb
= safe_realloc(0, sizeof(Blob
));
2302 memset(g
.pFirstDb
, 0, sizeof(Blob
));
2304 g
.pFirstDb
->seq
= 0;
2309 /* Print the description, if there is one */
2310 if( !quietFlag
&& !bScript
){
2311 zDbName
= azSrcDb
[iSrcDb
];
2312 i
= (int)strlen(zDbName
) - 1;
2313 while( i
>0 && zDbName
[i
-1]!='/' && zDbName
[i
-1]!='\\' ){ i
--; }
2316 sqlite3_prepare_v2(db
, "SELECT msg FROM readme", -1, &pStmt
, 0);
2317 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
2318 printf("%s: %s\n", zDbName
, sqlite3_column_text(pStmt
,0));
2320 sqlite3_finalize(pStmt
);
2324 /* Rebuild the database, if requested */
2327 printf("%s: rebuilding... ", zDbName
);
2330 rebuild_database(db
, 0);
2331 if( !quietFlag
) printf("done\n");
2334 /* Close the source database. Verify that no SQLite memory allocations are
2338 if( sqlite3_memory_used()>0 ){
2339 fatalError("SQLite has memory in use before the start of testing");
2342 /* Limit available memory, if requested */
2345 if( nMemThisDb
>0 && nMem
==0 ){
2346 if( !nativeMalloc
){
2347 pHeap
= realloc(pHeap
, nMemThisDb
);
2349 fatalError("failed to allocate %d bytes of heap memory", nMem
);
2351 sqlite3_config(SQLITE_CONFIG_HEAP
, pHeap
, nMemThisDb
, 128);
2353 sqlite3_hard_heap_limit64((sqlite3_int64
)nMemThisDb
);
2356 sqlite3_hard_heap_limit64(0);
2359 /* Disable lookaside with the --native-malloc option */
2361 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, 0, 0);
2364 /* Reset the in-memory virtual filesystem */
2367 /* Run a test using each SQL script against each database.
2369 if( verboseFlag
<2 && !quietFlag
&& !bSpinner
&& !bScript
){
2370 printf("%s:", zDbName
);
2372 for(pSql
=g
.pFirstSql
; pSql
; pSql
=pSql
->pNext
){
2373 tmStart
= timeOfDay();
2374 if( isDbSql(pSql
->a
, pSql
->sz
) ){
2375 sqlite3_snprintf(sizeof(g
.zTestName
), g
.zTestName
, "sqlid=%d",pSql
->id
);
2377 /* No progress output */
2378 }else if( bSpinner
){
2380 int idx
= pSql
->seq
;
2381 printf("\r%s: %d/%d ", zDbName
, idx
, nTotal
);
2383 }else if( verboseFlag
>1 ){
2384 printf("%s\n", g
.zTestName
);
2386 }else if( !quietFlag
){
2387 static int prevAmt
= -1;
2388 int idx
= pSql
->seq
;
2389 int amt
= idx
*10/(g
.nSql
);
2391 printf(" %d%%", amt
*10);
2399 runCombinedDbSqlInput(pSql
->a
, pSql
->sz
, iTimeout
, bScript
, pSql
->id
);
2402 if( bTimer
&& !bScript
){
2403 sqlite3_int64 tmEnd
= timeOfDay();
2404 printf("%lld %s\n", tmEnd
- tmStart
, g
.zTestName
);
2410 for(pDb
=g
.pFirstDb
; pDb
; pDb
=pDb
->pNext
){
2412 const char *zVfs
= "inmem";
2413 sqlite3_snprintf(sizeof(g
.zTestName
), g
.zTestName
, "sqlid=%d,dbid=%d",
2416 /* No progress output */
2417 }else if( bSpinner
){
2418 int nTotal
= g
.nDb
*g
.nSql
;
2419 int idx
= pSql
->seq
*g
.nDb
+ pDb
->id
- 1;
2420 printf("\r%s: %d/%d ", zDbName
, idx
, nTotal
);
2422 }else if( verboseFlag
>1 ){
2423 printf("%s\n", g
.zTestName
);
2425 }else if( !quietFlag
){
2426 static int prevAmt
= -1;
2427 int idx
= pSql
->seq
*g
.nDb
+ pDb
->id
- 1;
2428 int amt
= idx
*10/(g
.nDb
*g
.nSql
);
2430 printf(" %d%%", amt
*10);
2441 sqlite3_snprintf(sizeof(zName
), zName
, "db%06d.db",
2442 pDb
->id
>1 ? pDb
->id
: pSql
->id
);
2443 renderDbSqlForCLI(stdout
, zName
,
2444 pDb
->a
, pDb
->sz
, pSql
->a
, pSql
->sz
);
2447 createVFile("main.db", pDb
->sz
, pDb
->a
);
2448 sqlite3_randomness(0,0);
2449 if( ossFuzzThisDb
){
2450 #ifndef SQLITE_OSS_FUZZ
2451 fatalError("--oss-fuzz not supported: recompile"
2452 " with -DSQLITE_OSS_FUZZ");
2454 extern int LLVMFuzzerTestOneInput(const uint8_t*, size_t);
2455 LLVMFuzzerTestOneInput((const uint8_t*)pSql
->a
, (size_t)pSql
->sz
);
2458 openFlags
= SQLITE_OPEN_CREATE
| SQLITE_OPEN_READWRITE
;
2459 if( nativeFlag
&& pDb
->sz
==0 ){
2460 openFlags
|= SQLITE_OPEN_MEMORY
;
2463 rc
= sqlite3_open_v2("main.db", &db
, openFlags
, zVfs
);
2464 if( rc
) fatalError("cannot open inmem database");
2465 sqlite3_limit(db
, SQLITE_LIMIT_LENGTH
, 100000000);
2466 sqlite3_limit(db
, SQLITE_LIMIT_LIKE_PATTERN_LENGTH
, 50);
2467 if( cellSzCkFlag
) runSql(db
, "PRAGMA cell_size_check=ON", runFlags
);
2468 setAlarm((iTimeout
+999)/1000);
2469 /* Enable test functions */
2470 sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
, db
);
2471 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
2472 if( sqlFuzz
|| vdbeLimitFlag
){
2473 sqlite3_progress_handler(db
, 100000, progressHandler
,
2477 #ifdef SQLITE_TESTCTRL_PRNG_SEED
2478 sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED
, 1, db
);
2481 sqlite3_exec(db
, "PRAGMA vdbe_debug=ON", 0, 0, 0);
2484 runSql(db
, (char*)pSql
->a
, runFlags
);
2485 }while( timeoutTest
);
2487 sqlite3_exec(db
, "PRAGMA temp_store_directory=''", 0, 0, 0);
2490 if( sqlite3_memory_used()>0 ){
2491 fatalError("memory leak: %lld bytes outstanding",
2492 sqlite3_memory_used());
2497 sqlite3_int64 tmEnd
= timeOfDay();
2498 printf("%lld %s\n", tmEnd
- tmStart
, g
.zTestName
);
2502 /* Simulate an error if the TEST_FAILURE environment variable is "5".
2503 ** This is used to verify that automated test script really do spot
2504 ** errors that occur in this test program.
2507 if( zFailCode
[0]=='5' && zFailCode
[1]==0 ){
2508 fatalError("simulated failure");
2509 }else if( zFailCode
[0]!=0 ){
2510 /* If TEST_FAILURE is something other than 5, just exit the test
2512 printf("\nExit early due to TEST_FAILURE being set\n");
2514 goto sourcedb_cleanup
;
2520 /* No progress output */
2521 }else if( bSpinner
){
2522 int nTotal
= g
.nDb
*g
.nSql
;
2523 printf("\r%s: %d/%d \n", zDbName
, nTotal
, nTotal
);
2524 }else if( !quietFlag
&& verboseFlag
<2 ){
2525 printf(" 100%% - %d tests\n", g
.nDb
*g
.nSql
);
2528 /* Clean up at the end of processing a single source database
2531 blobListFree(g
.pFirstSql
);
2532 blobListFree(g
.pFirstDb
);
2535 } /* End loop over all source databases */
2537 if( !quietFlag
&& !bScript
){
2538 sqlite3_int64 iElapse
= timeOfDay() - iBegin
;
2540 printf("fuzzcheck: %u query invariants checked\n", g
.nInvariant
);
2542 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
2543 "SQLite %s %s (%d-bit)\n",
2544 nTest
, (int)(iElapse
/1000), (int)(iElapse
%1000),
2545 sqlite3_libversion(), sqlite3_sourceid(),
2546 8*(int)sizeof(char*));