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