xref: /sqlite-3.40.0/test/fuzzcheck.c (revision 3f09beda)
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.
10 **
11 *************************************************************************
12 **
13 ** This is a utility program designed to aid running regressions tests on
14 ** the SQLite library using data from an external fuzzer, such as American
15 ** Fuzzy Lop (AFL) (http://lcamtuf.coredump.cx/afl/).
16 **
17 ** This program reads content from an SQLite database file with the following
18 ** schema:
19 **
20 **     CREATE TABLE db(
21 **       dbid INTEGER PRIMARY KEY, -- database id
22 **       dbcontent BLOB            -- database disk file image
23 **     );
24 **     CREATE TABLE xsql(
25 **       sqlid INTEGER PRIMARY KEY,   -- SQL script id
26 **       sqltext TEXT                 -- Text of SQL statements to run
27 **     );
28 **     CREATE TABLE IF NOT EXISTS readme(
29 **       msg TEXT -- Human-readable description of this test collection
30 **     );
31 **
32 ** For each database file in the DB table, the SQL text in the XSQL table
33 ** is run against that database.  All README.MSG values are printed prior
34 ** to the start of the test (unless the --quiet option is used).  If the
35 ** DB table is empty, then all entries in XSQL are run against an empty
36 ** in-memory database.
37 **
38 ** This program is looking for crashes, assertion faults, and/or memory leaks.
39 ** No attempt is made to verify the output.  The assumption is that either all
40 ** of the database files or all of the SQL statements are malformed inputs,
41 ** generated by a fuzzer, that need to be checked to make sure they do not
42 ** present a security risk.
43 **
44 ** This program also includes some command-line options to help with
45 ** creation and maintenance of the source content database.  The command
46 **
47 **     ./fuzzcheck database.db --load-sql FILE...
48 **
49 ** Loads all FILE... arguments into the XSQL table.  The --load-db option
50 ** works the same but loads the files into the DB table.  The -m option can
51 ** be used to initialize the README table.  The "database.db" file is created
52 ** if it does not previously exist.  Example:
53 **
54 **     ./fuzzcheck new.db --load-sql *.sql
55 **     ./fuzzcheck new.db --load-db *.db
56 **     ./fuzzcheck new.db -m 'New test cases'
57 **
58 ** The three commands above will create the "new.db" file and initialize all
59 ** tables.  Then do "./fuzzcheck new.db" to run the tests.
60 **
61 ** DEBUGGING HINTS:
62 **
63 ** If fuzzcheck does crash, it can be run in the debugger and the content
64 ** of the global variable g.zTextName[] will identify the specific XSQL and
65 ** DB values that were running when the crash occurred.
66 */
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <stdarg.h>
71 #include <ctype.h>
72 #include "sqlite3.h"
73 
74 #ifdef __unix__
75 # include <signal.h>
76 # include <unistd.h>
77 #endif
78 
79 /*
80 ** Files in the virtual file system.
81 */
82 typedef struct VFile VFile;
83 struct VFile {
84   char *zFilename;        /* Filename.  NULL for delete-on-close. From malloc() */
85   int sz;                 /* Size of the file in bytes */
86   int nRef;               /* Number of references to this file */
87   unsigned char *a;       /* Content of the file.  From malloc() */
88 };
89 typedef struct VHandle VHandle;
90 struct VHandle {
91   sqlite3_file base;      /* Base class.  Must be first */
92   VFile *pVFile;          /* The underlying file */
93 };
94 
95 /*
96 ** The value of a database file template, or of an SQL script
97 */
98 typedef struct Blob Blob;
99 struct Blob {
100   Blob *pNext;            /* Next in a list */
101   int id;                 /* Id of this Blob */
102   int seq;                /* Sequence number */
103   int sz;                 /* Size of this Blob in bytes */
104   unsigned char a[1];     /* Blob content.  Extra space allocated as needed. */
105 };
106 
107 /*
108 ** Maximum number of files in the in-memory virtual filesystem.
109 */
110 #define MX_FILE  10
111 
112 /*
113 ** Maximum allowed file size
114 */
115 #define MX_FILE_SZ 10000000
116 
117 /*
118 ** All global variables are gathered into the "g" singleton.
119 */
120 static struct GlobalVars {
121   const char *zArgv0;              /* Name of program */
122   VFile aFile[MX_FILE];            /* The virtual filesystem */
123   int nDb;                         /* Number of template databases */
124   Blob *pFirstDb;                  /* Content of first template database */
125   int nSql;                        /* Number of SQL scripts */
126   Blob *pFirstSql;                 /* First SQL script */
127   char zTestName[100];             /* Name of current test */
128 } g;
129 
130 /*
131 ** Print an error message and quit.
132 */
133 static void fatalError(const char *zFormat, ...){
134   va_list ap;
135   if( g.zTestName[0] ){
136     fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
137   }else{
138     fprintf(stderr, "%s: ", g.zArgv0);
139   }
140   va_start(ap, zFormat);
141   vfprintf(stderr, zFormat, ap);
142   va_end(ap);
143   fprintf(stderr, "\n");
144   exit(1);
145 }
146 
147 /*
148 ** Timeout handler
149 */
150 #ifdef __unix__
151 static void timeoutHandler(int NotUsed){
152   (void)NotUsed;
153   fatalError("timeout\n");
154 }
155 #endif
156 
157 /*
158 ** Set the an alarm to go off after N seconds.  Disable the alarm
159 ** if N==0
160 */
161 static void setAlarm(int N){
162 #ifdef __unix__
163   alarm(N);
164 #else
165   (void)N;
166 #endif
167 }
168 
169 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
170 /*
171 ** This an SQL progress handler.  After an SQL statement has run for
172 ** many steps, we want to interrupt it.  This guards against infinite
173 ** loops from recursive common table expressions.
174 **
175 ** *pVdbeLimitFlag is true if the --limit-vdbe command-line option is used.
176 ** In that case, hitting the progress handler is a fatal error.
177 */
178 static int progressHandler(void *pVdbeLimitFlag){
179   if( *(int*)pVdbeLimitFlag ) fatalError("too many VDBE cycles");
180   return 1;
181 }
182 #endif
183 
184 /*
185 ** Reallocate memory.  Show and error and quit if unable.
186 */
187 static void *safe_realloc(void *pOld, int szNew){
188   void *pNew = realloc(pOld, szNew);
189   if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
190   return pNew;
191 }
192 
193 /*
194 ** Initialize the virtual file system.
195 */
196 static void formatVfs(void){
197   int i;
198   for(i=0; i<MX_FILE; i++){
199     g.aFile[i].sz = -1;
200     g.aFile[i].zFilename = 0;
201     g.aFile[i].a = 0;
202     g.aFile[i].nRef = 0;
203   }
204 }
205 
206 
207 /*
208 ** Erase all information in the virtual file system.
209 */
210 static void reformatVfs(void){
211   int i;
212   for(i=0; i<MX_FILE; i++){
213     if( g.aFile[i].sz<0 ) continue;
214     if( g.aFile[i].zFilename ){
215       free(g.aFile[i].zFilename);
216       g.aFile[i].zFilename = 0;
217     }
218     if( g.aFile[i].nRef>0 ){
219       fatalError("file %d still open.  nRef=%d", i, g.aFile[i].nRef);
220     }
221     g.aFile[i].sz = -1;
222     free(g.aFile[i].a);
223     g.aFile[i].a = 0;
224     g.aFile[i].nRef = 0;
225   }
226 }
227 
228 /*
229 ** Find a VFile by name
230 */
231 static VFile *findVFile(const char *zName){
232   int i;
233   if( zName==0 ) return 0;
234   for(i=0; i<MX_FILE; i++){
235     if( g.aFile[i].zFilename==0 ) continue;
236     if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
237   }
238   return 0;
239 }
240 
241 /*
242 ** Find a VFile by name.  Create it if it does not already exist and
243 ** initialize it to the size and content given.
244 **
245 ** Return NULL only if the filesystem is full.
246 */
247 static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
248   VFile *pNew = findVFile(zName);
249   int i;
250   if( pNew ) return pNew;
251   for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
252   if( i>=MX_FILE ) return 0;
253   pNew = &g.aFile[i];
254   if( zName ){
255     pNew->zFilename = safe_realloc(0, strlen(zName)+1);
256     memcpy(pNew->zFilename, zName, strlen(zName)+1);
257   }else{
258     pNew->zFilename = 0;
259   }
260   pNew->nRef = 0;
261   pNew->sz = sz;
262   pNew->a = safe_realloc(0, sz);
263   if( sz>0 ) memcpy(pNew->a, pData, sz);
264   return pNew;
265 }
266 
267 
268 /*
269 ** Implementation of the "readfile(X)" SQL function.  The entire content
270 ** of the file named X is read and returned as a BLOB.  NULL is returned
271 ** if the file does not exist or is unreadable.
272 */
273 static void readfileFunc(
274   sqlite3_context *context,
275   int argc,
276   sqlite3_value **argv
277 ){
278   const char *zName;
279   FILE *in;
280   long nIn;
281   void *pBuf;
282 
283   zName = (const char*)sqlite3_value_text(argv[0]);
284   if( zName==0 ) return;
285   in = fopen(zName, "rb");
286   if( in==0 ) return;
287   fseek(in, 0, SEEK_END);
288   nIn = ftell(in);
289   rewind(in);
290   pBuf = sqlite3_malloc64( nIn );
291   if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
292     sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
293   }else{
294     sqlite3_free(pBuf);
295   }
296   fclose(in);
297 }
298 
299 /*
300 ** Load a list of Blob objects from the database
301 */
302 static void blobListLoadFromDb(
303   sqlite3 *db,             /* Read from this database */
304   const char *zSql,        /* Query used to extract the blobs */
305   int onlyId,              /* Only load where id is this value */
306   int *pN,                 /* OUT: Write number of blobs loaded here */
307   Blob **ppList            /* OUT: Write the head of the blob list here */
308 ){
309   Blob head;
310   Blob *p;
311   sqlite3_stmt *pStmt;
312   int n = 0;
313   int rc;
314   char *z2;
315 
316   if( onlyId>0 ){
317     z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
318   }else{
319     z2 = sqlite3_mprintf("%s", zSql);
320   }
321   rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
322   sqlite3_free(z2);
323   if( rc ) fatalError("%s", sqlite3_errmsg(db));
324   head.pNext = 0;
325   p = &head;
326   while( SQLITE_ROW==sqlite3_step(pStmt) ){
327     int sz = sqlite3_column_bytes(pStmt, 1);
328     Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
329     pNew->id = sqlite3_column_int(pStmt, 0);
330     pNew->sz = sz;
331     pNew->seq = n++;
332     pNew->pNext = 0;
333     memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
334     pNew->a[sz] = 0;
335     p->pNext = pNew;
336     p = pNew;
337   }
338   sqlite3_finalize(pStmt);
339   *pN = n;
340   *ppList = head.pNext;
341 }
342 
343 /*
344 ** Free a list of Blob objects
345 */
346 static void blobListFree(Blob *p){
347   Blob *pNext;
348   while( p ){
349     pNext = p->pNext;
350     free(p);
351     p = pNext;
352   }
353 }
354 
355 
356 /* Return the current wall-clock time */
357 static sqlite3_int64 timeOfDay(void){
358   static sqlite3_vfs *clockVfs = 0;
359   sqlite3_int64 t;
360   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
361   if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
362     clockVfs->xCurrentTimeInt64(clockVfs, &t);
363   }else{
364     double r;
365     clockVfs->xCurrentTime(clockVfs, &r);
366     t = (sqlite3_int64)(r*86400000.0);
367   }
368   return t;
369 }
370 
371 /* Methods for the VHandle object
372 */
373 static int inmemClose(sqlite3_file *pFile){
374   VHandle *p = (VHandle*)pFile;
375   VFile *pVFile = p->pVFile;
376   pVFile->nRef--;
377   if( pVFile->nRef==0 && pVFile->zFilename==0 ){
378     pVFile->sz = -1;
379     free(pVFile->a);
380     pVFile->a = 0;
381   }
382   return SQLITE_OK;
383 }
384 static int inmemRead(
385   sqlite3_file *pFile,   /* Read from this open file */
386   void *pData,           /* Store content in this buffer */
387   int iAmt,              /* Bytes of content */
388   sqlite3_int64 iOfst    /* Start reading here */
389 ){
390   VHandle *pHandle = (VHandle*)pFile;
391   VFile *pVFile = pHandle->pVFile;
392   if( iOfst<0 || iOfst>=pVFile->sz ){
393     memset(pData, 0, iAmt);
394     return SQLITE_IOERR_SHORT_READ;
395   }
396   if( iOfst+iAmt>pVFile->sz ){
397     memset(pData, 0, iAmt);
398     iAmt = (int)(pVFile->sz - iOfst);
399     memcpy(pData, pVFile->a, iAmt);
400     return SQLITE_IOERR_SHORT_READ;
401   }
402   memcpy(pData, pVFile->a + iOfst, iAmt);
403   return SQLITE_OK;
404 }
405 static int inmemWrite(
406   sqlite3_file *pFile,   /* Write to this file */
407   const void *pData,     /* Content to write */
408   int iAmt,              /* bytes to write */
409   sqlite3_int64 iOfst    /* Start writing here */
410 ){
411   VHandle *pHandle = (VHandle*)pFile;
412   VFile *pVFile = pHandle->pVFile;
413   if( iOfst+iAmt > pVFile->sz ){
414     if( iOfst+iAmt >= MX_FILE_SZ ){
415       return SQLITE_FULL;
416     }
417     pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
418     if( iOfst > pVFile->sz ){
419       memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
420     }
421     pVFile->sz = (int)(iOfst + iAmt);
422   }
423   memcpy(pVFile->a + iOfst, pData, iAmt);
424   return SQLITE_OK;
425 }
426 static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
427   VHandle *pHandle = (VHandle*)pFile;
428   VFile *pVFile = pHandle->pVFile;
429   if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
430   return SQLITE_OK;
431 }
432 static int inmemSync(sqlite3_file *pFile, int flags){
433   return SQLITE_OK;
434 }
435 static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
436   *pSize = ((VHandle*)pFile)->pVFile->sz;
437   return SQLITE_OK;
438 }
439 static int inmemLock(sqlite3_file *pFile, int type){
440   return SQLITE_OK;
441 }
442 static int inmemUnlock(sqlite3_file *pFile, int type){
443   return SQLITE_OK;
444 }
445 static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
446   *pOut = 0;
447   return SQLITE_OK;
448 }
449 static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
450   return SQLITE_NOTFOUND;
451 }
452 static int inmemSectorSize(sqlite3_file *pFile){
453   return 512;
454 }
455 static int inmemDeviceCharacteristics(sqlite3_file *pFile){
456   return
457       SQLITE_IOCAP_SAFE_APPEND |
458       SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
459       SQLITE_IOCAP_POWERSAFE_OVERWRITE;
460 }
461 
462 
463 /* Method table for VHandle
464 */
465 static sqlite3_io_methods VHandleMethods = {
466   /* iVersion  */    1,
467   /* xClose    */    inmemClose,
468   /* xRead     */    inmemRead,
469   /* xWrite    */    inmemWrite,
470   /* xTruncate */    inmemTruncate,
471   /* xSync     */    inmemSync,
472   /* xFileSize */    inmemFileSize,
473   /* xLock     */    inmemLock,
474   /* xUnlock   */    inmemUnlock,
475   /* xCheck... */    inmemCheckReservedLock,
476   /* xFileCtrl */    inmemFileControl,
477   /* xSectorSz */    inmemSectorSize,
478   /* xDevchar  */    inmemDeviceCharacteristics,
479   /* xShmMap   */    0,
480   /* xShmLock  */    0,
481   /* xShmBarrier */  0,
482   /* xShmUnmap */    0,
483   /* xFetch    */    0,
484   /* xUnfetch  */    0
485 };
486 
487 /*
488 ** Open a new file in the inmem VFS.  All files are anonymous and are
489 ** delete-on-close.
490 */
491 static int inmemOpen(
492   sqlite3_vfs *pVfs,
493   const char *zFilename,
494   sqlite3_file *pFile,
495   int openFlags,
496   int *pOutFlags
497 ){
498   VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
499   VHandle *pHandle = (VHandle*)pFile;
500   if( pVFile==0 ){
501     return SQLITE_FULL;
502   }
503   pHandle->pVFile = pVFile;
504   pVFile->nRef++;
505   pFile->pMethods = &VHandleMethods;
506   if( pOutFlags ) *pOutFlags = openFlags;
507   return SQLITE_OK;
508 }
509 
510 /*
511 ** Delete a file by name
512 */
513 static int inmemDelete(
514   sqlite3_vfs *pVfs,
515   const char *zFilename,
516   int syncdir
517 ){
518   VFile *pVFile = findVFile(zFilename);
519   if( pVFile==0 ) return SQLITE_OK;
520   if( pVFile->nRef==0 ){
521     free(pVFile->zFilename);
522     pVFile->zFilename = 0;
523     pVFile->sz = -1;
524     free(pVFile->a);
525     pVFile->a = 0;
526     return SQLITE_OK;
527   }
528   return SQLITE_IOERR_DELETE;
529 }
530 
531 /* Check for the existance of a file
532 */
533 static int inmemAccess(
534   sqlite3_vfs *pVfs,
535   const char *zFilename,
536   int flags,
537   int *pResOut
538 ){
539   VFile *pVFile = findVFile(zFilename);
540   *pResOut =  pVFile!=0;
541   return SQLITE_OK;
542 }
543 
544 /* Get the canonical pathname for a file
545 */
546 static int inmemFullPathname(
547   sqlite3_vfs *pVfs,
548   const char *zFilename,
549   int nOut,
550   char *zOut
551 ){
552   sqlite3_snprintf(nOut, zOut, "%s", zFilename);
553   return SQLITE_OK;
554 }
555 
556 /* GetLastError() is never used */
557 static int inmemGetLastError(sqlite3_vfs *pVfs, int n, char *z){
558   return SQLITE_OK;
559 }
560 
561 /*
562 ** Register the VFS that reads from the g.aFile[] set of files.
563 */
564 static void inmemVfsRegister(void){
565   static sqlite3_vfs inmemVfs;
566   sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
567   inmemVfs.iVersion = 1;
568   inmemVfs.szOsFile = sizeof(VHandle);
569   inmemVfs.mxPathname = 200;
570   inmemVfs.zName = "inmem";
571   inmemVfs.xOpen = inmemOpen;
572   inmemVfs.xDelete = inmemDelete;
573   inmemVfs.xAccess = inmemAccess;
574   inmemVfs.xFullPathname = inmemFullPathname;
575   inmemVfs.xRandomness = pDefault->xRandomness;
576   inmemVfs.xSleep = pDefault->xSleep;
577   inmemVfs.xCurrentTime = pDefault->xCurrentTime;
578   inmemVfs.xGetLastError = inmemGetLastError;
579   sqlite3_vfs_register(&inmemVfs, 0);
580 };
581 
582 /*
583 ** Allowed values for the runFlags parameter to runSql()
584 */
585 #define SQL_TRACE  0x0001     /* Print each SQL statement as it is prepared */
586 #define SQL_OUTPUT 0x0002     /* Show the SQL output */
587 
588 /*
589 ** Run multiple commands of SQL.  Similar to sqlite3_exec(), but does not
590 ** stop if an error is encountered.
591 */
592 static void runSql(sqlite3 *db, const char *zSql, unsigned  runFlags){
593   const char *zMore;
594   sqlite3_stmt *pStmt;
595 
596   while( zSql && zSql[0] ){
597     zMore = 0;
598     pStmt = 0;
599     sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
600     if( zMore==zSql ) break;
601     if( runFlags & SQL_TRACE ){
602       const char *z = zSql;
603       int n;
604       while( z<zMore && isspace(z[0]) ) z++;
605       n = (int)(zMore - z);
606       while( n>0 && isspace(z[n-1]) ) n--;
607       if( n==0 ) break;
608       if( pStmt==0 ){
609         printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
610       }else{
611         printf("TRACE: %.*s\n", n, z);
612       }
613     }
614     zSql = zMore;
615     if( pStmt ){
616       if( (runFlags & SQL_OUTPUT)==0 ){
617         while( SQLITE_ROW==sqlite3_step(pStmt) ){}
618       }else{
619         int nCol = -1;
620         while( SQLITE_ROW==sqlite3_step(pStmt) ){
621           int i;
622           if( nCol<0 ){
623             nCol = sqlite3_column_count(pStmt);
624           }else if( nCol>0 ){
625             printf("--------------------------------------------\n");
626           }
627           for(i=0; i<nCol; i++){
628             int eType = sqlite3_column_type(pStmt,i);
629             printf("%s = ", sqlite3_column_name(pStmt,i));
630             switch( eType ){
631               case SQLITE_NULL: {
632                 printf("NULL\n");
633                 break;
634               }
635               case SQLITE_INTEGER: {
636                 printf("INT %s\n", sqlite3_column_text(pStmt,i));
637                 break;
638               }
639               case SQLITE_FLOAT: {
640                 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
641                 break;
642               }
643               case SQLITE_TEXT: {
644                 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
645                 break;
646               }
647               case SQLITE_BLOB: {
648                 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
649                 break;
650               }
651             }
652           }
653         }
654       }
655       sqlite3_finalize(pStmt);
656     }
657   }
658 }
659 
660 /*
661 ** Rebuild the database file.
662 **
663 **    (1)  Remove duplicate entries
664 **    (2)  Put all entries in order
665 **    (3)  Vacuum
666 */
667 static void rebuild_database(sqlite3 *db){
668   int rc;
669   rc = sqlite3_exec(db,
670      "BEGIN;\n"
671      "CREATE TEMP TABLE dbx AS SELECT DISTINCT dbcontent FROM db;\n"
672      "DELETE FROM db;\n"
673      "INSERT INTO db(dbid, dbcontent) SELECT NULL, dbcontent FROM dbx ORDER BY 2;\n"
674      "DROP TABLE dbx;\n"
675      "CREATE TEMP TABLE sx AS SELECT DISTINCT sqltext FROM xsql;\n"
676      "DELETE FROM xsql;\n"
677      "INSERT INTO xsql(sqlid,sqltext) SELECT NULL, sqltext FROM sx ORDER BY 2;\n"
678      "DROP TABLE sx;\n"
679      "COMMIT;\n"
680      "PRAGMA page_size=1024;\n"
681      "VACUUM;\n", 0, 0, 0);
682   if( rc ) fatalError("cannot rebuild: %s", sqlite3_errmsg(db));
683 }
684 
685 /*
686 ** Print sketchy documentation for this utility program
687 */
688 static void showHelp(void){
689   printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
690   printf(
691 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
692 "each database, checking for crashes and memory leaks.\n"
693 "Options:\n"
694 "  --cell-size-check     Set the PRAGMA cell_size_check=ON\n"
695 "  --dbid N              Use only the database where dbid=N\n"
696 "  --help                Show this help text\n"
697 "  -q                    Reduced output\n"
698 "  --quiet               Reduced output\n"
699 "  --limit-vdbe          Panic if an sync SQL runs for more than 100,000 cycles\n"
700 "  --load-sql ARGS...    Load SQL scripts fro files into SOURCE-DB\n"
701 "  --load-db ARGS...     Load template databases from files into SOURCE_DB\n"
702 "  -m TEXT               Add a description to the database\n"
703 "  --native-vfs          Use the native VFS for initially empty database files\n"
704 "  --rebuild             Rebuild and vacuum the database file\n"
705 "  --result-trace        Show the results of each SQL command\n"
706 "  --sqlid N             Use only SQL where sqlid=N\n"
707 "  --timeline N          Abort if any single test case needs more than N seconds\n"
708 "  -v                    Increased output\n"
709 "  --verbose             Increased output\n"
710   );
711 }
712 
713 int main(int argc, char **argv){
714   sqlite3_int64 iBegin;        /* Start time of this program */
715   int quietFlag = 0;           /* True if --quiet or -q */
716   int verboseFlag = 0;         /* True if --verbose or -v */
717   char *zInsSql = 0;           /* SQL statement for --load-db or --load-sql */
718   int iFirstInsArg = 0;        /* First argv[] to use for --load-db or --load-sql */
719   sqlite3 *db = 0;             /* The open database connection */
720   sqlite3_stmt *pStmt;         /* A prepared statement */
721   int rc;                      /* Result code from SQLite interface calls */
722   Blob *pSql;                  /* For looping over SQL scripts */
723   Blob *pDb;                   /* For looping over template databases */
724   int i;                       /* Loop index for the argv[] loop */
725   int onlySqlid = -1;          /* --sqlid */
726   int onlyDbid = -1;           /* --dbid */
727   int nativeFlag = 0;          /* --native-vfs */
728   int rebuildFlag = 0;         /* --rebuild */
729   int vdbeLimitFlag = 0;       /* --limit-vdbe */
730   int timeoutTest = 0;         /* undocumented --timeout-test flag */
731   int runFlags = 0;            /* Flags sent to runSql() */
732   char *zMsg = 0;              /* Add this message */
733   int nSrcDb = 0;              /* Number of source databases */
734   char **azSrcDb = 0;          /* Array of source database names */
735   int iSrcDb;                  /* Loop over all source databases */
736   int nTest = 0;               /* Total number of tests performed */
737   char *zDbName = "";          /* Appreviated name of a source database */
738   const char *zFailCode = 0;   /* Value of the TEST_FAILURE environment variable */
739   int cellSzCkFlag = 0;        /* --cell-size-check */
740   int sqlFuzz = 0;             /* True for SQL fuzz testing. False for DB fuzz */
741   int iTimeout = 120;          /* Default 120-second timeout */
742 
743   iBegin = timeOfDay();
744 #ifdef __unix__
745   signal(SIGALRM, timeoutHandler);
746 #endif
747   g.zArgv0 = argv[0];
748   zFailCode = getenv("TEST_FAILURE");
749   for(i=1; i<argc; i++){
750     const char *z = argv[i];
751     if( z[0]=='-' ){
752       z++;
753       if( z[0]=='-' ) z++;
754       if( strcmp(z,"cell-size-check")==0 ){
755         cellSzCkFlag = 1;
756       }else
757       if( strcmp(z,"dbid")==0 ){
758         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
759         onlyDbid = atoi(argv[++i]);
760       }else
761       if( strcmp(z,"help")==0 ){
762         showHelp();
763         return 0;
764       }else
765       if( strcmp(z,"limit-vdbe")==0 ){
766         vdbeLimitFlag = 1;
767       }else
768       if( strcmp(z,"load-sql")==0 ){
769         zInsSql = "INSERT INTO xsql(sqltext) VALUES(CAST(readfile(?1) AS text))";
770         iFirstInsArg = i+1;
771         break;
772       }else
773       if( strcmp(z,"load-db")==0 ){
774         zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
775         iFirstInsArg = i+1;
776         break;
777       }else
778       if( strcmp(z,"m")==0 ){
779         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
780         zMsg = argv[++i];
781       }else
782       if( strcmp(z,"native-vfs")==0 ){
783         nativeFlag = 1;
784       }else
785       if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
786         quietFlag = 1;
787         verboseFlag = 0;
788       }else
789       if( strcmp(z,"rebuild")==0 ){
790         rebuildFlag = 1;
791       }else
792       if( strcmp(z,"result-trace")==0 ){
793         runFlags |= SQL_OUTPUT;
794       }else
795       if( strcmp(z,"sqlid")==0 ){
796         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
797         onlySqlid = atoi(argv[++i]);
798       }else
799       if( strcmp(z,"timeout")==0 ){
800         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
801         iTimeout = atoi(argv[++i]);
802       }else
803       if( strcmp(z,"timeout-test")==0 ){
804         timeoutTest = 1;
805 #ifndef __unix__
806         fatalError("timeout is not available on non-unix systems");
807 #endif
808       }else
809       if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
810         quietFlag = 0;
811         verboseFlag = 1;
812         runFlags |= SQL_TRACE;
813       }else
814       {
815         fatalError("unknown option: %s", argv[i]);
816       }
817     }else{
818       nSrcDb++;
819       azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
820       azSrcDb[nSrcDb-1] = argv[i];
821     }
822   }
823   if( nSrcDb==0 ) fatalError("no source database specified");
824   if( nSrcDb>1 ){
825     if( zMsg ){
826       fatalError("cannot change the description of more than one database");
827     }
828     if( zInsSql ){
829       fatalError("cannot import into more than one database");
830     }
831   }
832 
833   /* Process each source database separately */
834   for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
835     rc = sqlite3_open(azSrcDb[iSrcDb], &db);
836     if( rc ){
837       fatalError("cannot open source database %s - %s",
838       azSrcDb[iSrcDb], sqlite3_errmsg(db));
839     }
840     rc = sqlite3_exec(db,
841        "CREATE TABLE IF NOT EXISTS db(\n"
842        "  dbid INTEGER PRIMARY KEY, -- database id\n"
843        "  dbcontent BLOB            -- database disk file image\n"
844        ");\n"
845        "CREATE TABLE IF NOT EXISTS xsql(\n"
846        "  sqlid INTEGER PRIMARY KEY,   -- SQL script id\n"
847        "  sqltext TEXT                 -- Text of SQL statements to run\n"
848        ");"
849        "CREATE TABLE IF NOT EXISTS readme(\n"
850        "  msg TEXT -- Human-readable description of this file\n"
851        ");", 0, 0, 0);
852     if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
853     if( zMsg ){
854       char *zSql;
855       zSql = sqlite3_mprintf(
856                "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
857       rc = sqlite3_exec(db, zSql, 0, 0, 0);
858       sqlite3_free(zSql);
859       if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
860     }
861     if( zInsSql ){
862       sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
863                               readfileFunc, 0, 0);
864       rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
865       if( rc ) fatalError("cannot prepare statement [%s]: %s",
866                           zInsSql, sqlite3_errmsg(db));
867       rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
868       if( rc ) fatalError("cannot start a transaction");
869       for(i=iFirstInsArg; i<argc; i++){
870         sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
871         sqlite3_step(pStmt);
872         rc = sqlite3_reset(pStmt);
873         if( rc ) fatalError("insert failed for %s", argv[i]);
874       }
875       sqlite3_finalize(pStmt);
876       rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
877       if( rc ) fatalError("cannot commit the transaction: %s", sqlite3_errmsg(db));
878       rebuild_database(db);
879       sqlite3_close(db);
880       return 0;
881     }
882 
883     /* Load all SQL script content and all initial database images from the
884     ** source db
885     */
886     blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
887                            &g.nSql, &g.pFirstSql);
888     if( g.nSql==0 ) fatalError("need at least one SQL script");
889     blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
890                        &g.nDb, &g.pFirstDb);
891     if( g.nDb==0 ){
892       g.pFirstDb = safe_realloc(0, sizeof(Blob));
893       memset(g.pFirstDb, 0, sizeof(Blob));
894       g.pFirstDb->id = 1;
895       g.pFirstDb->seq = 0;
896       g.nDb = 1;
897       sqlFuzz = 1;
898     }
899 
900     /* Print the description, if there is one */
901     if( !quietFlag ){
902       int i;
903       zDbName = azSrcDb[iSrcDb];
904       i = strlen(zDbName) - 1;
905       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
906       zDbName += i;
907       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
908       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
909         printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
910       }
911       sqlite3_finalize(pStmt);
912     }
913 
914     /* Rebuild the database, if requested */
915     if( rebuildFlag ){
916       if( !quietFlag ){
917         printf("%s: rebuilding... ", zDbName);
918         fflush(stdout);
919       }
920       rebuild_database(db);
921       if( !quietFlag ) printf("done\n");
922     }
923 
924     /* Close the source database.  Verify that no SQLite memory allocations are
925     ** outstanding.
926     */
927     sqlite3_close(db);
928     if( sqlite3_memory_used()>0 ){
929       fatalError("SQLite has memory in use before the start of testing");
930     }
931 
932     /* Register the in-memory virtual filesystem
933     */
934     formatVfs();
935     inmemVfsRegister();
936 
937     /* Run a test using each SQL script against each database.
938     */
939     if( !verboseFlag && !quietFlag ) printf("%s:", zDbName);
940     for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
941       for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
942         int openFlags;
943         const char *zVfs = "inmem";
944         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
945                          pSql->id, pDb->id);
946         if( verboseFlag ){
947           printf("%s\n", g.zTestName);
948           fflush(stdout);
949         }else if( !quietFlag ){
950           static int prevAmt = -1;
951           int idx = pSql->seq*g.nDb + pDb->id - 1;
952           int amt = idx*10/(g.nDb*g.nSql);
953           if( amt!=prevAmt ){
954             printf(" %d%%", amt*10);
955             fflush(stdout);
956             prevAmt = amt;
957           }
958         }
959         createVFile("main.db", pDb->sz, pDb->a);
960         openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
961         if( nativeFlag && pDb->sz==0 ){
962           openFlags |= SQLITE_OPEN_MEMORY;
963           zVfs = 0;
964         }
965         rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
966         if( rc ) fatalError("cannot open inmem database");
967         if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
968         setAlarm(iTimeout);
969 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
970         if( sqlFuzz || vdbeLimitFlag ){
971           sqlite3_progress_handler(db, 100000, progressHandler, &vdbeLimitFlag);
972         }
973 #endif
974         do{
975           runSql(db, (char*)pSql->a, runFlags);
976         }while( timeoutTest );
977         setAlarm(0);
978         sqlite3_close(db);
979         if( sqlite3_memory_used()>0 ) fatalError("memory leak");
980         reformatVfs();
981         nTest++;
982         g.zTestName[0] = 0;
983 
984         /* Simulate an error if the TEST_FAILURE environment variable is "5".
985         ** This is used to verify that automated test script really do spot
986         ** errors that occur in this test program.
987         */
988         if( zFailCode ){
989           if( zFailCode[0]=='5' && zFailCode[1]==0 ){
990             fatalError("simulated failure");
991           }else if( zFailCode[0]!=0 ){
992             /* If TEST_FAILURE is something other than 5, just exit the test
993             ** early */
994             printf("\nExit early due to TEST_FAILURE being set\n");
995             iSrcDb = nSrcDb-1;
996             goto sourcedb_cleanup;
997           }
998         }
999       }
1000     }
1001     if( !quietFlag && !verboseFlag ){
1002       printf(" 100%% - %d tests\n", g.nDb*g.nSql);
1003     }
1004 
1005     /* Clean up at the end of processing a single source database
1006     */
1007   sourcedb_cleanup:
1008     blobListFree(g.pFirstSql);
1009     blobListFree(g.pFirstDb);
1010     reformatVfs();
1011 
1012   } /* End loop over all source databases */
1013 
1014   if( !quietFlag ){
1015     sqlite3_int64 iElapse = timeOfDay() - iBegin;
1016     printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
1017            "SQLite %s %s\n",
1018            nTest, (int)(iElapse/1000), (int)(iElapse%1000),
1019            sqlite3_libversion(), sqlite3_sourceid());
1020   }
1021   free(azSrcDb);
1022   return 0;
1023 }
1024