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