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