xref: /sqlite-3.40.0/test/fuzzcheck.c (revision 4dfe98a8)
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 ** Return the value of a hexadecimal digit.  Return -1 if the input
687 ** is not a hex digit.
688 */
689 static int hexDigitValue(char c){
690   if( c>='0' && c<='9' ) return c - '0';
691   if( c>='a' && c<='f' ) return c - 'a' + 10;
692   if( c>='A' && c<='F' ) return c - 'A' + 10;
693   return -1;
694 }
695 
696 /*
697 ** Interpret zArg as an integer value, possibly with suffixes.
698 */
699 static int integerValue(const char *zArg){
700   sqlite3_int64 v = 0;
701   static const struct { char *zSuffix; int iMult; } aMult[] = {
702     { "KiB", 1024 },
703     { "MiB", 1024*1024 },
704     { "GiB", 1024*1024*1024 },
705     { "KB",  1000 },
706     { "MB",  1000000 },
707     { "GB",  1000000000 },
708     { "K",   1000 },
709     { "M",   1000000 },
710     { "G",   1000000000 },
711   };
712   int i;
713   int isNeg = 0;
714   if( zArg[0]=='-' ){
715     isNeg = 1;
716     zArg++;
717   }else if( zArg[0]=='+' ){
718     zArg++;
719   }
720   if( zArg[0]=='0' && zArg[1]=='x' ){
721     int x;
722     zArg += 2;
723     while( (x = hexDigitValue(zArg[0]))>=0 ){
724       v = (v<<4) + x;
725       zArg++;
726     }
727   }else{
728     while( isdigit(zArg[0]) ){
729       v = v*10 + zArg[0] - '0';
730       zArg++;
731     }
732   }
733   for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
734     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
735       v *= aMult[i].iMult;
736       break;
737     }
738   }
739   if( v>0x7fffffff ) fatalError("parameter too large - max 2147483648");
740   return (int)(isNeg? -v : v);
741 }
742 
743 /*
744 ** Print sketchy documentation for this utility program
745 */
746 static void showHelp(void){
747   printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
748   printf(
749 "Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
750 "each database, checking for crashes and memory leaks.\n"
751 "Options:\n"
752 "  --cell-size-check     Set the PRAGMA cell_size_check=ON\n"
753 "  --dbid N              Use only the database where dbid=N\n"
754 "  --help                Show this help text\n"
755 "  -q                    Reduced output\n"
756 "  --quiet               Reduced output\n"
757 "  --limit-mem N         Limit memory used by test SQLite instance to N bytes\n"
758 "  --limit-vdbe          Panic if an sync SQL runs for more than 100,000 cycles\n"
759 "  --load-sql ARGS...    Load SQL scripts fro files into SOURCE-DB\n"
760 "  --load-db ARGS...     Load template databases from files into SOURCE_DB\n"
761 "  -m TEXT               Add a description to the database\n"
762 "  --native-vfs          Use the native VFS for initially empty database files\n"
763 "  --rebuild             Rebuild and vacuum the database file\n"
764 "  --result-trace        Show the results of each SQL command\n"
765 "  --sqlid N             Use only SQL where sqlid=N\n"
766 "  --timeline N          Abort if any single test case needs more than N seconds\n"
767 "  -v                    Increased output\n"
768 "  --verbose             Increased output\n"
769   );
770 }
771 
772 int main(int argc, char **argv){
773   sqlite3_int64 iBegin;        /* Start time of this program */
774   int quietFlag = 0;           /* True if --quiet or -q */
775   int verboseFlag = 0;         /* True if --verbose or -v */
776   char *zInsSql = 0;           /* SQL statement for --load-db or --load-sql */
777   int iFirstInsArg = 0;        /* First argv[] to use for --load-db or --load-sql */
778   sqlite3 *db = 0;             /* The open database connection */
779   sqlite3_stmt *pStmt;         /* A prepared statement */
780   int rc;                      /* Result code from SQLite interface calls */
781   Blob *pSql;                  /* For looping over SQL scripts */
782   Blob *pDb;                   /* For looping over template databases */
783   int i;                       /* Loop index for the argv[] loop */
784   int onlySqlid = -1;          /* --sqlid */
785   int onlyDbid = -1;           /* --dbid */
786   int nativeFlag = 0;          /* --native-vfs */
787   int rebuildFlag = 0;         /* --rebuild */
788   int vdbeLimitFlag = 0;       /* --limit-vdbe */
789   int timeoutTest = 0;         /* undocumented --timeout-test flag */
790   int runFlags = 0;            /* Flags sent to runSql() */
791   char *zMsg = 0;              /* Add this message */
792   int nSrcDb = 0;              /* Number of source databases */
793   char **azSrcDb = 0;          /* Array of source database names */
794   int iSrcDb;                  /* Loop over all source databases */
795   int nTest = 0;               /* Total number of tests performed */
796   char *zDbName = "";          /* Appreviated name of a source database */
797   const char *zFailCode = 0;   /* Value of the TEST_FAILURE environment variable */
798   int cellSzCkFlag = 0;        /* --cell-size-check */
799   int sqlFuzz = 0;             /* True for SQL fuzz testing. False for DB fuzz */
800   int iTimeout = 120;          /* Default 120-second timeout */
801   int nMem = 0;                /* Memory limit */
802 
803   iBegin = timeOfDay();
804 #ifdef __unix__
805   signal(SIGALRM, timeoutHandler);
806 #endif
807   g.zArgv0 = argv[0];
808   zFailCode = getenv("TEST_FAILURE");
809   for(i=1; i<argc; i++){
810     const char *z = argv[i];
811     if( z[0]=='-' ){
812       z++;
813       if( z[0]=='-' ) z++;
814       if( strcmp(z,"cell-size-check")==0 ){
815         cellSzCkFlag = 1;
816       }else
817       if( strcmp(z,"dbid")==0 ){
818         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
819         onlyDbid = integerValue(argv[++i]);
820       }else
821       if( strcmp(z,"help")==0 ){
822         showHelp();
823         return 0;
824       }else
825       if( strcmp(z,"limit-mem")==0 ){
826         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
827         nMem = integerValue(argv[++i]);
828       }else
829       if( strcmp(z,"limit-vdbe")==0 ){
830         vdbeLimitFlag = 1;
831       }else
832       if( strcmp(z,"load-sql")==0 ){
833         zInsSql = "INSERT INTO xsql(sqltext) VALUES(CAST(readfile(?1) AS text))";
834         iFirstInsArg = i+1;
835         break;
836       }else
837       if( strcmp(z,"load-db")==0 ){
838         zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
839         iFirstInsArg = i+1;
840         break;
841       }else
842       if( strcmp(z,"m")==0 ){
843         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
844         zMsg = argv[++i];
845       }else
846       if( strcmp(z,"native-vfs")==0 ){
847         nativeFlag = 1;
848       }else
849       if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
850         quietFlag = 1;
851         verboseFlag = 0;
852       }else
853       if( strcmp(z,"rebuild")==0 ){
854         rebuildFlag = 1;
855       }else
856       if( strcmp(z,"result-trace")==0 ){
857         runFlags |= SQL_OUTPUT;
858       }else
859       if( strcmp(z,"sqlid")==0 ){
860         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
861         onlySqlid = integerValue(argv[++i]);
862       }else
863       if( strcmp(z,"timeout")==0 ){
864         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
865         iTimeout = integerValue(argv[++i]);
866       }else
867       if( strcmp(z,"timeout-test")==0 ){
868         timeoutTest = 1;
869 #ifndef __unix__
870         fatalError("timeout is not available on non-unix systems");
871 #endif
872       }else
873       if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
874         quietFlag = 0;
875         verboseFlag = 1;
876         runFlags |= SQL_TRACE;
877       }else
878       {
879         fatalError("unknown option: %s", argv[i]);
880       }
881     }else{
882       nSrcDb++;
883       azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
884       azSrcDb[nSrcDb-1] = argv[i];
885     }
886   }
887   if( nSrcDb==0 ) fatalError("no source database specified");
888   if( nSrcDb>1 ){
889     if( zMsg ){
890       fatalError("cannot change the description of more than one database");
891     }
892     if( zInsSql ){
893       fatalError("cannot import into more than one database");
894     }
895   }
896 
897   /* Process each source database separately */
898   for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
899     rc = sqlite3_open(azSrcDb[iSrcDb], &db);
900     if( rc ){
901       fatalError("cannot open source database %s - %s",
902       azSrcDb[iSrcDb], sqlite3_errmsg(db));
903     }
904     rc = sqlite3_exec(db,
905        "CREATE TABLE IF NOT EXISTS db(\n"
906        "  dbid INTEGER PRIMARY KEY, -- database id\n"
907        "  dbcontent BLOB            -- database disk file image\n"
908        ");\n"
909        "CREATE TABLE IF NOT EXISTS xsql(\n"
910        "  sqlid INTEGER PRIMARY KEY,   -- SQL script id\n"
911        "  sqltext TEXT                 -- Text of SQL statements to run\n"
912        ");"
913        "CREATE TABLE IF NOT EXISTS readme(\n"
914        "  msg TEXT -- Human-readable description of this file\n"
915        ");", 0, 0, 0);
916     if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
917     if( zMsg ){
918       char *zSql;
919       zSql = sqlite3_mprintf(
920                "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
921       rc = sqlite3_exec(db, zSql, 0, 0, 0);
922       sqlite3_free(zSql);
923       if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
924     }
925     if( zInsSql ){
926       sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
927                               readfileFunc, 0, 0);
928       rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
929       if( rc ) fatalError("cannot prepare statement [%s]: %s",
930                           zInsSql, sqlite3_errmsg(db));
931       rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
932       if( rc ) fatalError("cannot start a transaction");
933       for(i=iFirstInsArg; i<argc; i++){
934         sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
935         sqlite3_step(pStmt);
936         rc = sqlite3_reset(pStmt);
937         if( rc ) fatalError("insert failed for %s", argv[i]);
938       }
939       sqlite3_finalize(pStmt);
940       rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
941       if( rc ) fatalError("cannot commit the transaction: %s", sqlite3_errmsg(db));
942       rebuild_database(db);
943       sqlite3_close(db);
944       return 0;
945     }
946 
947     /* Load all SQL script content and all initial database images from the
948     ** source db
949     */
950     blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
951                            &g.nSql, &g.pFirstSql);
952     if( g.nSql==0 ) fatalError("need at least one SQL script");
953     blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
954                        &g.nDb, &g.pFirstDb);
955     if( g.nDb==0 ){
956       g.pFirstDb = safe_realloc(0, sizeof(Blob));
957       memset(g.pFirstDb, 0, sizeof(Blob));
958       g.pFirstDb->id = 1;
959       g.pFirstDb->seq = 0;
960       g.nDb = 1;
961       sqlFuzz = 1;
962     }
963 
964     /* Print the description, if there is one */
965     if( !quietFlag ){
966       int i;
967       zDbName = azSrcDb[iSrcDb];
968       i = strlen(zDbName) - 1;
969       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
970       zDbName += i;
971       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
972       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
973         printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
974       }
975       sqlite3_finalize(pStmt);
976     }
977 
978     /* Rebuild the database, if requested */
979     if( rebuildFlag ){
980       if( !quietFlag ){
981         printf("%s: rebuilding... ", zDbName);
982         fflush(stdout);
983       }
984       rebuild_database(db);
985       if( !quietFlag ) printf("done\n");
986     }
987 
988     /* Close the source database.  Verify that no SQLite memory allocations are
989     ** outstanding.
990     */
991     sqlite3_close(db);
992     if( sqlite3_memory_used()>0 ){
993       fatalError("SQLite has memory in use before the start of testing");
994     }
995 
996     /* Limit available memory, if requested */
997     if( nMem>0 ){
998       void *pHeap;
999       sqlite3_shutdown();
1000       pHeap = malloc(nMem);
1001       if( pHeap==0 ){
1002         fatalError("failed to allocate %d bytes of heap memory", nMem);
1003       }
1004       sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMem, 128);
1005     }
1006 
1007     /* Register the in-memory virtual filesystem
1008     */
1009     formatVfs();
1010     inmemVfsRegister();
1011 
1012     /* Run a test using each SQL script against each database.
1013     */
1014     if( !verboseFlag && !quietFlag ) printf("%s:", zDbName);
1015     for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
1016       for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
1017         int openFlags;
1018         const char *zVfs = "inmem";
1019         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
1020                          pSql->id, pDb->id);
1021         if( verboseFlag ){
1022           printf("%s\n", g.zTestName);
1023           fflush(stdout);
1024         }else if( !quietFlag ){
1025           static int prevAmt = -1;
1026           int idx = pSql->seq*g.nDb + pDb->id - 1;
1027           int amt = idx*10/(g.nDb*g.nSql);
1028           if( amt!=prevAmt ){
1029             printf(" %d%%", amt*10);
1030             fflush(stdout);
1031             prevAmt = amt;
1032           }
1033         }
1034         createVFile("main.db", pDb->sz, pDb->a);
1035         openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
1036         if( nativeFlag && pDb->sz==0 ){
1037           openFlags |= SQLITE_OPEN_MEMORY;
1038           zVfs = 0;
1039         }
1040         rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
1041         if( rc ) fatalError("cannot open inmem database");
1042         if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
1043         setAlarm(iTimeout);
1044 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1045         if( sqlFuzz || vdbeLimitFlag ){
1046           sqlite3_progress_handler(db, 100000, progressHandler, &vdbeLimitFlag);
1047         }
1048 #endif
1049         do{
1050           runSql(db, (char*)pSql->a, runFlags);
1051         }while( timeoutTest );
1052         setAlarm(0);
1053         sqlite3_close(db);
1054         if( sqlite3_memory_used()>0 ) fatalError("memory leak");
1055         reformatVfs();
1056         nTest++;
1057         g.zTestName[0] = 0;
1058 
1059         /* Simulate an error if the TEST_FAILURE environment variable is "5".
1060         ** This is used to verify that automated test script really do spot
1061         ** errors that occur in this test program.
1062         */
1063         if( zFailCode ){
1064           if( zFailCode[0]=='5' && zFailCode[1]==0 ){
1065             fatalError("simulated failure");
1066           }else if( zFailCode[0]!=0 ){
1067             /* If TEST_FAILURE is something other than 5, just exit the test
1068             ** early */
1069             printf("\nExit early due to TEST_FAILURE being set\n");
1070             iSrcDb = nSrcDb-1;
1071             goto sourcedb_cleanup;
1072           }
1073         }
1074       }
1075     }
1076     if( !quietFlag && !verboseFlag ){
1077       printf(" 100%% - %d tests\n", g.nDb*g.nSql);
1078     }
1079 
1080     /* Clean up at the end of processing a single source database
1081     */
1082   sourcedb_cleanup:
1083     blobListFree(g.pFirstSql);
1084     blobListFree(g.pFirstDb);
1085     reformatVfs();
1086 
1087   } /* End loop over all source databases */
1088 
1089   if( !quietFlag ){
1090     sqlite3_int64 iElapse = timeOfDay() - iBegin;
1091     printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
1092            "SQLite %s %s\n",
1093            nTest, (int)(iElapse/1000), (int)(iElapse%1000),
1094            sqlite3_libversion(), sqlite3_sourceid());
1095   }
1096   free(azSrcDb);
1097   return 0;
1098 }
1099