xref: /sqlite-3.40.0/test/fuzzcheck.c (revision cd423525)
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 !defined(SQLITE_ENABLE_MEMSYS3) && !defined(SQLITE_ENABLE_MEMSYS5)
869         fatalError("the %s option requires -DSQLITE_ENABLE_MEMSYS5 or _MEMSYS3",
870                    argv[i]);
871 #else
872         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
873         nMem = integerValue(argv[++i]);
874 #endif
875       }else
876       if( strcmp(z,"limit-vdbe")==0 ){
877         vdbeLimitFlag = 1;
878       }else
879       if( strcmp(z,"load-sql")==0 ){
880         zInsSql = "INSERT INTO xsql(sqltext) VALUES(CAST(readfile(?1) AS text))";
881         iFirstInsArg = i+1;
882         break;
883       }else
884       if( strcmp(z,"load-db")==0 ){
885         zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
886         iFirstInsArg = i+1;
887         break;
888       }else
889       if( strcmp(z,"m")==0 ){
890         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
891         zMsg = argv[++i];
892       }else
893       if( strcmp(z,"native-vfs")==0 ){
894         nativeFlag = 1;
895       }else
896       if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
897         quietFlag = 1;
898         verboseFlag = 0;
899       }else
900       if( strcmp(z,"rebuild")==0 ){
901         rebuildFlag = 1;
902       }else
903       if( strcmp(z,"result-trace")==0 ){
904         runFlags |= SQL_OUTPUT;
905       }else
906       if( strcmp(z,"sqlid")==0 ){
907         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
908         onlySqlid = integerValue(argv[++i]);
909       }else
910       if( strcmp(z,"timeout")==0 ){
911         if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
912         iTimeout = integerValue(argv[++i]);
913       }else
914       if( strcmp(z,"timeout-test")==0 ){
915         timeoutTest = 1;
916 #ifndef __unix__
917         fatalError("timeout is not available on non-unix systems");
918 #endif
919       }else
920       if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
921         quietFlag = 0;
922         verboseFlag = 1;
923         runFlags |= SQL_TRACE;
924       }else
925       {
926         fatalError("unknown option: %s", argv[i]);
927       }
928     }else{
929       nSrcDb++;
930       azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
931       azSrcDb[nSrcDb-1] = argv[i];
932     }
933   }
934   if( nSrcDb==0 ) fatalError("no source database specified");
935   if( nSrcDb>1 ){
936     if( zMsg ){
937       fatalError("cannot change the description of more than one database");
938     }
939     if( zInsSql ){
940       fatalError("cannot import into more than one database");
941     }
942   }
943 
944   /* Process each source database separately */
945   for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
946     rc = sqlite3_open(azSrcDb[iSrcDb], &db);
947     if( rc ){
948       fatalError("cannot open source database %s - %s",
949       azSrcDb[iSrcDb], sqlite3_errmsg(db));
950     }
951     rc = sqlite3_exec(db,
952        "CREATE TABLE IF NOT EXISTS db(\n"
953        "  dbid INTEGER PRIMARY KEY, -- database id\n"
954        "  dbcontent BLOB            -- database disk file image\n"
955        ");\n"
956        "CREATE TABLE IF NOT EXISTS xsql(\n"
957        "  sqlid INTEGER PRIMARY KEY,   -- SQL script id\n"
958        "  sqltext TEXT                 -- Text of SQL statements to run\n"
959        ");"
960        "CREATE TABLE IF NOT EXISTS readme(\n"
961        "  msg TEXT -- Human-readable description of this file\n"
962        ");", 0, 0, 0);
963     if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
964     if( zMsg ){
965       char *zSql;
966       zSql = sqlite3_mprintf(
967                "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
968       rc = sqlite3_exec(db, zSql, 0, 0, 0);
969       sqlite3_free(zSql);
970       if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
971     }
972     if( zInsSql ){
973       sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
974                               readfileFunc, 0, 0);
975       rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
976       if( rc ) fatalError("cannot prepare statement [%s]: %s",
977                           zInsSql, sqlite3_errmsg(db));
978       rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
979       if( rc ) fatalError("cannot start a transaction");
980       for(i=iFirstInsArg; i<argc; i++){
981         sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
982         sqlite3_step(pStmt);
983         rc = sqlite3_reset(pStmt);
984         if( rc ) fatalError("insert failed for %s", argv[i]);
985       }
986       sqlite3_finalize(pStmt);
987       rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
988       if( rc ) fatalError("cannot commit the transaction: %s", sqlite3_errmsg(db));
989       rebuild_database(db);
990       sqlite3_close(db);
991       return 0;
992     }
993     if( zExpDb!=0 || zExpSql!=0 ){
994       sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
995                               writefileFunc, 0, 0);
996       if( zExpDb!=0 ){
997         const char *zExDb =
998           "SELECT writefile(printf('%s/db%06d.db',?1,dbid),dbcontent),"
999           "       dbid, printf('%s/db%06d.db',?1,dbid), length(dbcontent)"
1000           "  FROM db WHERE ?2<0 OR dbid=?2;";
1001         rc = sqlite3_prepare_v2(db, zExDb, -1, &pStmt, 0);
1002         if( rc ) fatalError("cannot prepare statement [%s]: %s",
1003                             zExDb, sqlite3_errmsg(db));
1004         sqlite3_bind_text64(pStmt, 1, zExpDb, strlen(zExpDb),
1005                             SQLITE_STATIC, SQLITE_UTF8);
1006         sqlite3_bind_int(pStmt, 2, onlyDbid);
1007         while( sqlite3_step(pStmt)==SQLITE_ROW ){
1008           printf("write db-%d (%d bytes) into %s\n",
1009              sqlite3_column_int(pStmt,1),
1010              sqlite3_column_int(pStmt,3),
1011              sqlite3_column_text(pStmt,2));
1012         }
1013         sqlite3_finalize(pStmt);
1014       }
1015       if( zExpSql!=0 ){
1016         const char *zExSql =
1017           "SELECT writefile(printf('%s/sql%06d.txt',?1,sqlid),sqltext),"
1018           "       sqlid, printf('%s/sql%06d.txt',?1,sqlid), length(sqltext)"
1019           "  FROM xsql WHERE ?2<0 OR sqlid=?2;";
1020         rc = sqlite3_prepare_v2(db, zExSql, -1, &pStmt, 0);
1021         if( rc ) fatalError("cannot prepare statement [%s]: %s",
1022                             zExSql, sqlite3_errmsg(db));
1023         sqlite3_bind_text64(pStmt, 1, zExpSql, strlen(zExpSql),
1024                             SQLITE_STATIC, SQLITE_UTF8);
1025         sqlite3_bind_int(pStmt, 2, onlySqlid);
1026         while( sqlite3_step(pStmt)==SQLITE_ROW ){
1027           printf("write sql-%d (%d bytes) into %s\n",
1028              sqlite3_column_int(pStmt,1),
1029              sqlite3_column_int(pStmt,3),
1030              sqlite3_column_text(pStmt,2));
1031         }
1032         sqlite3_finalize(pStmt);
1033       }
1034       sqlite3_close(db);
1035       return 0;
1036     }
1037 
1038     /* Load all SQL script content and all initial database images from the
1039     ** source db
1040     */
1041     blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
1042                            &g.nSql, &g.pFirstSql);
1043     if( g.nSql==0 ) fatalError("need at least one SQL script");
1044     blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
1045                        &g.nDb, &g.pFirstDb);
1046     if( g.nDb==0 ){
1047       g.pFirstDb = safe_realloc(0, sizeof(Blob));
1048       memset(g.pFirstDb, 0, sizeof(Blob));
1049       g.pFirstDb->id = 1;
1050       g.pFirstDb->seq = 0;
1051       g.nDb = 1;
1052       sqlFuzz = 1;
1053     }
1054 
1055     /* Print the description, if there is one */
1056     if( !quietFlag ){
1057       zDbName = azSrcDb[iSrcDb];
1058       i = strlen(zDbName) - 1;
1059       while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
1060       zDbName += i;
1061       sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
1062       if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
1063         printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
1064       }
1065       sqlite3_finalize(pStmt);
1066     }
1067 
1068     /* Rebuild the database, if requested */
1069     if( rebuildFlag ){
1070       if( !quietFlag ){
1071         printf("%s: rebuilding... ", zDbName);
1072         fflush(stdout);
1073       }
1074       rebuild_database(db);
1075       if( !quietFlag ) printf("done\n");
1076     }
1077 
1078     /* Close the source database.  Verify that no SQLite memory allocations are
1079     ** outstanding.
1080     */
1081     sqlite3_close(db);
1082     if( sqlite3_memory_used()>0 ){
1083       fatalError("SQLite has memory in use before the start of testing");
1084     }
1085 
1086     /* Limit available memory, if requested */
1087     if( nMem>0 ){
1088       sqlite3_shutdown();
1089       pHeap = malloc(nMem);
1090       if( pHeap==0 ){
1091         fatalError("failed to allocate %d bytes of heap memory", nMem);
1092       }
1093       sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nMem, 128);
1094     }
1095 
1096     /* Register the in-memory virtual filesystem
1097     */
1098     formatVfs();
1099     inmemVfsRegister();
1100 
1101     /* Run a test using each SQL script against each database.
1102     */
1103     if( !verboseFlag && !quietFlag ) printf("%s:", zDbName);
1104     for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
1105       for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
1106         int openFlags;
1107         const char *zVfs = "inmem";
1108         sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
1109                          pSql->id, pDb->id);
1110         if( verboseFlag ){
1111           printf("%s\n", g.zTestName);
1112           fflush(stdout);
1113         }else if( !quietFlag ){
1114           static int prevAmt = -1;
1115           int idx = pSql->seq*g.nDb + pDb->id - 1;
1116           int amt = idx*10/(g.nDb*g.nSql);
1117           if( amt!=prevAmt ){
1118             printf(" %d%%", amt*10);
1119             fflush(stdout);
1120             prevAmt = amt;
1121           }
1122         }
1123         createVFile("main.db", pDb->sz, pDb->a);
1124         openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
1125         if( nativeFlag && pDb->sz==0 ){
1126           openFlags |= SQLITE_OPEN_MEMORY;
1127           zVfs = 0;
1128         }
1129         rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
1130         if( rc ) fatalError("cannot open inmem database");
1131         if( cellSzCkFlag ) runSql(db, "PRAGMA cell_size_check=ON", runFlags);
1132         setAlarm(iTimeout);
1133 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1134         if( sqlFuzz || vdbeLimitFlag ){
1135           sqlite3_progress_handler(db, 100000, progressHandler, &vdbeLimitFlag);
1136         }
1137 #endif
1138         do{
1139           runSql(db, (char*)pSql->a, runFlags);
1140         }while( timeoutTest );
1141         setAlarm(0);
1142         sqlite3_close(db);
1143         if( sqlite3_memory_used()>0 ) fatalError("memory leak");
1144         reformatVfs();
1145         nTest++;
1146         g.zTestName[0] = 0;
1147 
1148         /* Simulate an error if the TEST_FAILURE environment variable is "5".
1149         ** This is used to verify that automated test script really do spot
1150         ** errors that occur in this test program.
1151         */
1152         if( zFailCode ){
1153           if( zFailCode[0]=='5' && zFailCode[1]==0 ){
1154             fatalError("simulated failure");
1155           }else if( zFailCode[0]!=0 ){
1156             /* If TEST_FAILURE is something other than 5, just exit the test
1157             ** early */
1158             printf("\nExit early due to TEST_FAILURE being set\n");
1159             iSrcDb = nSrcDb-1;
1160             goto sourcedb_cleanup;
1161           }
1162         }
1163       }
1164     }
1165     if( !quietFlag && !verboseFlag ){
1166       printf(" 100%% - %d tests\n", g.nDb*g.nSql);
1167     }
1168 
1169     /* Clean up at the end of processing a single source database
1170     */
1171   sourcedb_cleanup:
1172     blobListFree(g.pFirstSql);
1173     blobListFree(g.pFirstDb);
1174     reformatVfs();
1175 
1176   } /* End loop over all source databases */
1177 
1178   if( !quietFlag ){
1179     sqlite3_int64 iElapse = timeOfDay() - iBegin;
1180     printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
1181            "SQLite %s %s\n",
1182            nTest, (int)(iElapse/1000), (int)(iElapse%1000),
1183            sqlite3_libversion(), sqlite3_sourceid());
1184   }
1185   free(azSrcDb);
1186   free(pHeap);
1187   return 0;
1188 }
1189